如何在Node.js中一次将一个可读流传输到两个可写流中?

Eye*_*Eye 30 gzip zlib gzipstream node.js node.js-stream

目标是:

  1. 创建文件读取流.
  2. 把它管到gzip(zlib.createGzip())
  3. 然后将zlib输出的读取流传输到:

    1)HTTP response对象

    2)可写文件流以保存gzip压缩输出.

现在我可以做到3.1:

var gzip = zlib.createGzip(),
    sourceFileStream = fs.createReadStream(sourceFilePath),
    targetFileStream = fs.createWriteStream(targetFilePath);

response.setHeader('Content-Encoding', 'gzip');

sourceFileStream.pipe(gzip).pipe(response);
Run Code Online (Sandbox Code Playgroud)

...工作正常,但我还需要将gzip压缩数据保存到文件中,这样我就不需要每次都重新压缩,并能够直接将gzip压缩数据作为响应流.

那么如何在Node中一次将一个可读流传输到两个可写流中?

sourceFileStream.pipe(gzip).pipe(response).pipe(targetFileStream);在节点0.8.4工作?

hun*_*tis 48

管道链/分裂不像你在这里尝试那样工作,发送第一个到两个不同的后续步骤:

sourceFileStream.pipe(gzip).pipe(response);

但是,您可以将相同的可读流传输到两个可写流中,例如:

var fs = require('fs');

var source = fs.createReadStream('source.txt');
var dest1 = fs.createWriteStream('dest1.txt');
var dest2 = fs.createWriteStream('dest2.txt');

source.pipe(dest1);
source.pipe(dest2);
Run Code Online (Sandbox Code Playgroud)

  • 管道可以链接?如果你考虑到最后一个pipe()不能在第一个`raw`流上工作,请不.它不像在jQuery中链接到同一个对象.最后一个`管道(响应)`只接受来自`gzip`的输入而不是来自`raw`. (10认同)

Eye*_*Eye 13

我发现zlib返回一个可读的流,后来可以通过管道传输到其他多个流中.所以我做了以下解决上述问题:

var sourceFileStream = fs.createReadStream(sourceFile);
// Even though we could chain like
// sourceFileStream.pipe(zlib.createGzip()).pipe(response);
// we need a stream with a gzipped data to pipe to two
// other streams.
var gzip = sourceFileStream.pipe(zlib.createGzip());

// This will pipe the gzipped data to response object
// and automatically close the response object.
gzip.pipe(response);

// Then I can pipe the gzipped data to a file.
gzip.pipe(fs.createWriteStream(targetFilePath));
Run Code Online (Sandbox Code Playgroud)

  • Downvote.这是多余的,根本不添加任何新信息,实际上设法增加了混淆. (8认同)
  • 你无法将可写流传输到任何东西:https://github.com/nodejs/readable-stream/blob/master/lib/_stream_writable.js#L193你需要一个douplex或一个可读的流来做到这一点. (2认同)