通过不同的可读stream对相同的可写stream进行两次pipe道操作

我试图连接一个string和一个可读stream(可读stream指向一个文件,可能有多个数据块,即文件可能很大)到一个可写入的stream,以便可写入的stream可以最终写入到一个目的地。

我正在encryption文件的string和内容,然后对它们应用zlib压缩,最后我想pipe他们到可写入的stream。

要做到这一点,我可以:

a)将文件内容转换为一个string,然后连接string然后encryption,进行压缩,然后将其pipe道化为可写入的stream。 但这是不可能的,因为文件的大小可能很大,因此我不能将其内容转换为string。

b)我可以先encryption和压缩string,然后将string转换成stream,然后将其完全传输到可写入stream中,然后将文件内容传送到相同的可写入stream中。

为此,我写了这个:

var crypto = require('crypto'), algorithm = 'aes-256-ctr', password = 'd6FAjkdlfAjk'; var stream = require('stream'); var fs = require('fs'); var zlib = require('zlib'); // input file var r = fs.createReadStream('file.txt'); // zip content var zip = zlib.createGzip(); // encrypt content var encrypt = crypto.createCipheriv(algorithm, password, iv); var w = fs.createWriteStream('file.out'); // the string contents are being converted into a stream so that they can be piped var Readable = stream.Readable; var s = new Readable(); s._read = function noop() {}; s.push(hexiv+':'); s.push(null); s.pipe(zlib.createGzip()).pipe(w); // start pipe when 'end' event is encountered s.on('end', function(){ r.pipe(zip).pipe(encrypt).pipe(w); }); 

我观察到的是:

只有第一个pipe道成功完成, file.outstring写入file.out 。 第二个pipe道在输出目的地上没有任何区别。 起初,我认为这可能是由于pipe的asynchronous行为。 所以,因为这个原因,在第一条pipe道closures之后,我正在pipe理文件内容。 但是,我仍然没有得到理想的结果。

我想知道为什么会发生这样做的任何适当的方式。

find了为什么第二个pipe道可写入streamw不工作的原因。

当第一个configuration文件(w)结束时,w处的写入也会自动closures。

所以不要使用s.pipe(zlib.createGzip()).pipe(w); 我应该使用:

 s.pipe(zlib.createGzip()).pipe(w, {end: false}); 

如果{end:false}作为第二个parameter passing给pipe(),则说明pipe道完成后,写入操作不应该closures。