5

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?

Mr Cold
  • 1,565
  • 2
  • 19
  • 29

2 Answers2

5

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 () { ... });
Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54
  • Probably you are misunderstanding my point. I focus on the "chain". what you said works with A and B, but how about C if I have A.pipe(B).pipe(C)? – Mr Cold Aug 12 '15 at 12:35
  • Oh, I am sorry. You are right :) Thank you very much. – Mr Cold Aug 12 '15 at 12:40
1

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

Muhaimin Taib
  • 306
  • 2
  • 4