Search code examples
javascriptnode.jspipechain

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?


Solution

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