如何暂停和恢复流的NodeJS管道?

时间:2020-05-14 21:37:14

标签: javascript node.js stream

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

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

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

await pipeline(read, progress,write )

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

1 个答案:

答案 0 :(得分:0)

好-实际上很简单-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();

除了可写流之外,您可以在管道中的任何流上暂停。在progress上调用暂停将导致read到达highWaterMark后立即暂停Array.prototype.pop=Array.prototype.pop||function(){ const len = this.length; const itemToBePopped=this[len-1]; this.splice(len-1,1); return itemToBePopped; } (基本上在缓冲区已满时)。