Node.js 可读流结束事件
当可读流中没有可用数据可供使用时,会发出可读流中的“结束”事件。如果数据未完全消耗,则不会发出“结束”事件。这可以通过将流切换到流动模式来完成,或者通过一次又一次地调用 stream.read() 方法直到所有数据都被消耗完。
句法:
Event: 'end'
下面的示例说明了在 Node.js 中使用end 事件:
示例 1:
// Node.js program to demonstrate the
// readable end event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Instructions to read data
readable.on('readable', () => {
let chunk;
// Using while loop and calling
// read method
while (null !== (chunk = readable.read())) {
// Displaying the chunk
console.log(`read: ${chunk}`);
}
});
// Handling end event
readable.on('end', () => {
console.log('All the data is being consumed.');
});
console.log("Done...");
输出:
Done...
read: GeeksforGeeks
All the data is being consumed.
示例 2:
// Node.js program to demonstrate the
// readable end event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Handling end event
readable.on('end', () => {
console.log('All the data is being consumed.');
});
console.log("Done...");
输出:
Done...
在这里,由于未调用 stream.read() 方法,因此不会消耗所有数据,因此此处不会发出结束事件。
参考: https://nodejs.org/api/stream.html#stream_event_end