问题描述
目标是:
- 创建文件读取流.
- 将其放入gzip(
zlib.createGzip()
) -
然后将zlib输出的读取流通过管道传输到:
- Create a file read stream.
- Pipe it to gzip (
zlib.createGzip()
) Then pipe the read stream of zlib output to:
1)HTTP response
对象
2)和可写文件流,以保存压缩后的输出.
2) and writable file stream to save the gzipped output.
现在我可以降低到3.1:
Now I can do down to 3.1:
var gzip = zlib.createGzip(),
sourceFileStream = fs.createReadStream(sourceFilePath),
targetFileStream = fs.createWriteStream(targetFilePath);
response.setHeader('Content-Encoding', 'gzip');
sourceFileStream.pipe(gzip).pipe(response);
...效果很好,但我还需要将压缩后的数据保存到文件中,这样我就不必每次都进行zip压缩并能够直接将压缩后的数据流式传输为回应.
... which works fine, but I need to also save the gzipped data to a file so that I don't need to regzip every time and be able to directly stream the gzipped data as a response.
那么,如何在Node中一次将一个可读流传送到两个可写流中?
sourceFileStream.pipe(gzip).pipe(response).pipe(targetFileStream);
是否可以在Node 0.8.x中工作?
Would sourceFileStream.pipe(gzip).pipe(response).pipe(targetFileStream);
work in Node 0.8.x?
推荐答案
我发现zlib返回了一个可读流,该流随后可以通过管道传递到其他多个流中.因此,我执行以下操作来解决上述问题:
I found that zlib returns a readable stream which can be later piped into multiple other streams. So I did the following to solve the above problem:
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));
这篇关于如何在Node.js中一次将一个可读流传输到两个可写流中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!