将转换stream应用于写入stream而不控制读取stream?

我有一个函数,期望我正在提供以下stream的写入stream:

const logStream = fs.createWriteStream('./log.txt') fn(logStream) 

fn由第三方模块提供,所以我不控制它的实现。 在内部,我知道fn最终这样做:

 // super simplified fn (logStream) { // ... stream.pipe(logStream, { end: true }) // ... } 

我的问题是,我知道读取stream的stream包含ANSI转义代码,我不希望被输出到我的log.txt 。 快速谷歌search后,我发现了chalk/strip-ansi-stream ,这是一个转换streamdevise来做到这一点。

所以,作为节点stream新手,我决定尝试修改我的代码:

 const stripAnsiStream = require('strip-ansi-stream') const logStream = fs.createWriteStream('./log.txt') fn(stripAnsiStream().pipe(logStream)) 

…这不起作用:我的日志文件仍然包含ANSI转义代码的内容 。 我认为这是因为,而不是像创build一个链

 a.pipe(b).pipe(c) 

我已经完成了

 a.pipe(b.pipe(c)) 

如何将这个转换stream应用于我的写入stream而不控制提供读取stream的pipe道链的开始?

为了链接,stream.pipe()返回input参数。 b.pipe(c)的返回值是c

当你调用fn(b.pipe(c)) ,你实际上绕过了变换streamb ,直接input了写入streamc

案例#1:a.pipe(b.pipe(c))

 b.pipe(c) a.pipe(c) 

案例#2:a.pipe(b).pipe(c)

 a.pipe(b) b.pipe(c) 

转换stream可以传送到日志stream中,然后单独传递到模块中。 您正在有效地使用案例#2,但以相反的顺序启动pipe道。

 const stripAnsiStream = require('strip-ansi-stream') const fn = require('my-third-party-module') const transformStream = stripAnsiStream() const logStream = fs.createWriteStream('./log.txt') transformStream.pipe(logStream) fn(transformStream)