For example, I have this:
var r = fs.createReadStream('file.txt');
var z = zlib.createGzip();
var w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
I want to do something after r.pipe(z).pipe(w) finishes. I tried something like this:
var r = A.pipe(B);
r.on('end', function () { ... });
but it doesn't work for a pipe chain. How can I make it work?
For example, I have this:
var r = fs.createReadStream('file.txt');
var z = zlib.createGzip();
var w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
I want to do something after r.pipe(z).pipe(w) finishes. I tried something like this:
var r = A.pipe(B);
r.on('end', function () { ... });
but it doesn't work for a pipe chain. How can I make it work?
Share asked Aug 12, 2015 at 12:03 Mr ColdMr Cold 1,5733 gold badges19 silver badges29 bronze badges2 Answers
Reset to default 5You're looking for the finish
event. From the docs:
When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.
When the source stream emits an end
, it calls end()
on the destination, which in your case, is B
. So you can do:
var r = A.pipe(B);
r.on('finish', function () { ... });
There's a new NodeJS operator called pipeline
introduced in v10.
I've listened to one of the speech given by Nodejs Stream contributor, they've introduced this feature intended to 'replace' these Writable.pipe()
and Readable.pipe()
, because pipeline
will automatically close all the chaining stream when there's error preventing memory leak. The old operator will still be there to avoid breaking the previous version and most of us are using it.
For your use case, I suggest you need to use v14 as according to the docs, pipeline
will wait for the close event before invoking the callback.
https://nodejs/api/stream.html#stream_stream_pipeline_streams_callback