Node.js 可读流暂停事件
当调用 stream.pause() 并且readableFlowing属性不为 false 时,会发出可读流中的“暂停”事件。
句法:
Event: 'pause'
返回值:如果 readable.pause() 被调用,则发出,否则不发出。
下面的例子说明了 Node.js 中暂停事件的使用:
示例 1:
// Node.js program to demonstrate the
// readable pause event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
readable.on('data', (chunk) => {
console.log(`${chunk}`);
});
// Handling pause event
readable.on("pause", () => {
console.log("pause emitted!");
});
// Calling pause method
readable.pause();
console.log("Program ends....");
输出:
pause emitted!
Program ends....
示例 2:
// Node.js program to demonstrate the
// readable pause event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
readable.on('data', (chunk) => {
console.log(`${chunk}`);
});
// Handling pause event
readable.on("pause", () => {
console.log("pause emitted!");
});
console.log("Program ends....");
输出:
Program ends....
GeeksforGeeks
这里没有调用 pause() 方法,因此不会发出 pause 事件。
参考: https://nodejs.org/api/stream.html#stream_event_pause