📜  Node.js stream.Writable 关闭事件

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

Node.js stream.Writable 关闭事件

stream.Writable 关闭事件是 Stream 模块的内置应用程序编程接口,用于在关闭流及其任何隐藏资源(例如,文件描述符)时发出。此事件意味着不会发出更多事件,并且不会发生进一步的计算。

句法:

Event: 'close'

返回值:如果在此事件之后调用 writable.destroy() 方法或关闭文件描述符,则发出此事件,否则不发出。

下面的例子说明了 Node.js 中stream.Writable close 事件的使用:

示例 1:

// Node.js program to demonstrate the     
// close 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('GeeksforGeeks');
  
// Emitting close event
writable.on('close', () => {
    console.log("No further operations will be performed!");
});
  
// Calling destroy function
writable.destroy();
  
// Shows that the program ends
console.log("program is ended.");

输出:

GeeksforGeeks
program is ended.
No further operations will be performed!

在上面的示例中,在关闭事件之后调用 writable.destroy() 方法,因此它被发出。

示例 2:

// Node.js program to demonstrate the     
// close 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('GeeksforGeeks');
  
// Emitting close event
writable.on('close', () => {
    console.log("No further operations will be performed!");
});
  
// Shows that the program ends
console.log("program is ended.");

输出:

GeeksforGeeks
program is ended.

因此,此处未调用 writable.destroy()函数,因此未执行关闭事件。

参考: https://nodejs.org/api/stream.html#stream_event_close