📜  Node.js 可写流完成事件

📅  最后修改于: 2022-05-13 01:56:47.756000             🧑  作者: Mango

Node.js 可写流完成事件

当所有数据都被刷新到隐藏系统时,可写流中的“完成”事件在调用 writable.end() 方法后发出。

句法:

Event: 'finish'

返回值:如果之前调用了 writable.end() 方法,则发出此事件,否则不发出。

下面的示例说明了 Node.js 中“完成”事件的使用:

示例 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.

在上面的例子中, writeable.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