简体   繁体   English

创建一个 node.js 可写流,将数据代理到另一个可写流,但首先添加一些自己的数据

[英]Creating a node.js writable stream that proxies data to another writable stream, but prepends some of its own data first

I have a writable stream that I would like to wrap with a stream of my own to prepend some data to whatever goes into the output stream.我有一个可写的流,我想用我自己的流包装它,以便在进入输出流的任何内容之前添加一些数据。

I would normally write inputStream.pipe(outputStream) , where inputStream would provide foo bar and outputStream would recieve foo bar .我通常会写inputStream.pipe(outputStream) ,其中inputStream将提供foo bar , outputStream 将接收foo bar

I would like to be able to write inputStream.pipe(proxyStream('prefix ', outputStream)) , where inputStream would provide foo bar , but outputStream would recieve prefix foo bar .我希望能够编写inputStream.pipe(proxyStream('prefix ', outputStream)) ,其中inputStream将提供foo bar ,但outputStream将接收prefix foo bar

I've tried the following code, but I get Error: write after end almost immediately after the pipe starts.我试过下面的代码,但我得到Error: write after end在管道启动Error: write after end几乎立即结束后Error: write after end

class DetectStream extends stream.Writable {
  constructor (prefix, output) {
    super();
    this._output = output;
    this._output.write(prefix, 'utf-8');
  }
  _write (chunk, enc, next) {
    this._output.write(chunk, enc, next);
  }
}

Why don't you just write to the outputStream before piping the inputStream into it?为什么不在将inputStream管道输入之前写入outputStream呢?

function proxyStream (prefix, output) {
  output.write(prefix, 'utf-8')
  return output
}

Then use it just like you said:然后像你说的那样使用它:

inputStream.pipe(proxyStream('prefix ', outputStream))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM