Eye*_*Eye 30 gzip zlib gzipstream node.js node.js-stream
目标是:
zlib.createGzip())然后将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)
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)
| 归档时间: |
|
| 查看次数: |
15105 次 |
| 最近记录: |