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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。