首页 > 解决方案 > 如何暂停和恢复 NodeJS 流管道?

问题描述

我正在使用 node 的 stream.pipleline 的承诺版本:

const pipeline = util.promisify(stream.pipeline);

//Create Read,Transform and Write streams....

await pipeline(read, progress,write )

我希望能够以编程方式暂停/恢复整个过程。如何在不破坏其中一个流的情况下实现这一点?

标签: javascriptnode.jsstream

解决方案


嗯 - 它实际上很简单 -在下面pipeline使用pipe并在流之间转发你的pause/resume逻辑,所以:

如果你想暂停阅读:

const pipeline = util.promisify(stream.pipeline);

//Create Read,Transform and Write streams....

await pipeline(read, progress,write )

// under some circumstances:
read.pause();
// and then, when you're ready just
read.resume();

您可以暂停管道中的任何流,但可写流除外。调用 pause onprogress将导致在到达时read立即暂停highWaterMark(基本上是在缓冲区已满时)。


推荐阅读