gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:59:33 25 4
gpt4 key购买 nike

目标是:

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

    1) HTTP 响应对象

    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);

... 效果很好,但我还需要将压缩后的数据保存到文件中,这样我就不需要每次都重新压缩并能够直接将压缩后的数据流式传输为回复。

那么如何在 Node 中将一个可读流同时通过管道传输到两个可写流?

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

最佳答案

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

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);

关于node.js - 如何在 Node.js 中一次将一个可读流传输到两个可写流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14173488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com