34

目标是:

  1. 创建文件读取流。
  2. 将其通过管道传输到 gzip ( zlib.createGzip())
  3. 然后将 zlib 输出的读取流通过管道传输到:

    1) HTTPresponse对象

    2)可写文件流来保存压缩后的输出。

现在我可以做到 3.1:

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

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

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

...效果很好,但我还需要将压缩后的数据保存到文件中,这样我就不需要每次都进行 regzip 并且能够直接流式传输压缩后的数据作为响应。

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

sourceFileStream.pipe(gzip).pipe(response).pipe(targetFileStream);可以在 Node 0.8.x 中工作吗?

4

3 回答 3

56

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

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);
于 2013-01-05T17:11:40.453 回答
17

我发现 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));
于 2013-02-03T04:04:25.520 回答
-1

您可以使用“可读流克隆”包

const fs = require("fs");
const ReadableStreamClone = require("readable-stream-clone");

const readStream = fs.createReadStream('text.txt');

const readStream1 = new ReadableStreamClone(readStream);
const readStream2 = new ReadableStreamClone(readStream);

const writeStream1 = fs.createWriteStream('sample1.txt');
const writeStream2 = fs.createWriteStream('sample2.txt');

readStream1.pipe(writeStream1)
readStream2.pipe(writeStream2)
于 2020-05-21T14:21:19.490 回答