當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Node.js Writable Stream finish事件用法及代碼示例


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




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | Writable Stream finish Event。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。