Writable Stream 中的 ‘finish’ 事件在调用 writable.end() 方法后,当所有数据都被刷新到隐藏系统时发出。
用法:
Event:'finish'
返回值:如果 writable.end() 方法在之前被调用,那么这个事件被发出,否则它不会被发出。
下面的例子说明了在 Node.js 中 ‘finish’ 事件的使用:
范例1:
// Node.js program to demonstrate the
// finish event
// Including stream module
const stream = require('stream');
// Creating a stream and creating
// a write function
const writable = new stream.Writable({
// Write function with its
// parameters
write:function(chunk, encoding, next) {
// Converting the chunk of
// data to string
console.log(chunk.toString());
next();
}
});
// Writing data
writable.write('hi');
// Calling end function
writable.end();
// Emitting finish event
writable.on('finish', function() {
console.log("Write is completed.");
});
// Displays that the program
// is ended
console.log("program is ended.");
输出:
hi program is ended. Write is completed.
在上面的例子中, writable.end() 方法在完成事件之前被调用,因此它被发出。
范例2:
// Node.js program to demonstrate the
// finish event
// Including stream module
const stream = require('stream');
// Creating a stream and creating
// a write function
const writable = new stream.Writable({
// Write function with its
// parameters
write:function(chunk, encoding, next) {
// Converting the chunk of
// data to string
console.log(chunk.toString());
next();
}
});
// Writing data
writable.write('hi');
// Emitting finish event
writable.on('finish', function() {
console.log("Write is completed.");
});
// Displays that the program
// is ended
console.log("program is ended.");
输出:
hi program is ended.
所以,这里 writable.end() 函数没有被调用,所以不执行完成事件。
参考: https://nodejs.org/api/stream.html#stream_event_finish
相关用法
- node.js Stream writable.writable用法及代码示例
- Node.js Writable Stream pipe事件用法及代码示例
- Node.js Writable Stream unpipe事件用法及代码示例
- node.js Stream writable.writableFinished用法及代码示例
- node.js Stream writable.writableObjectMode用法及代码示例
- node.js Stream writable.writableLength用法及代码示例
- node.js Stream writable.cork()用法及代码示例
- node.js Stream writable.writableHighWaterMark用法及代码示例
- node.js Stream writable.writableCorked用法及代码示例
- node.js Stream writable.write()用法及代码示例
- node.js Stream writable.end()用法及代码示例
- node.js Stream writable.writableEnded用法及代码示例
- node.js Stream writable.destroyed用法及代码示例
- node.js Stream writable.destroy()用法及代码示例
- node.js Stream writable.uncork()用法及代码示例
- node.js Stream writable.setDefaultEncoding()用法及代码示例
- Node.js Readable Stream readable事件用法及代码示例
- Node.js Readable Stream end事件用法及代码示例
- Node.js Readable Stream data事件用法及代码示例
注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 Node.js | Writable Stream finish Event。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。