Mr Cold
Mr Cold

Reputation: 1573

How to check completion of a pipe chain in node.js?

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?

Upvotes: 5

Views: 3042

Answers (2)

Muhaimin Taib
Muhaimin Taib

Reputation: 336

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.org/api/stream.html#stream_stream_pipeline_streams_callback

Upvotes: 1

Rodrigo Medeiros
Rodrigo Medeiros

Reputation: 7862

You'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 () { ... });

Upvotes: 5

Related Questions