最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check completion of a pipe chain in node.js? - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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 () { ... });

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

发布评论

评论列表(0)

  1. 暂无评论