'beforeExit' 事件


当 Node.js 清空其事件循环并且没有额外的工作要安排时,则会触发 'beforeExit' 事件。 通常情况下,当没有工作要调度时,Node.js 进程会退出,但是注册在 'beforeExit' 事件上的监听器可以进行异步的调用,从而使 Node.js 进程继续。

调用监听器回调函数时将 process.exitCode 的值作为唯一的参数传入。

对于导致显式终止的条件,例如调用 process.exit() 或未捕获的异常,则不会触发 'beforeExit' 事件。

'beforeExit' 不应用作 'exit' 事件的替代,除非打算安排额外的工作。

process.on('beforeExit', (code) => {
  console.log('Process beforeExit event with code: ', code);
});

process.on('exit', (code) => {
  console.log('Process exit event with code: ', code);
});

console.log('This message is displayed first.');

// 打印:
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0

The 'beforeExit' event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the 'beforeExit' event can make asynchronous calls, and thereby cause the Node.js process to continue.

The listener callback function is invoked with the value of process.exitCode passed as the only argument.

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

The 'beforeExit' should not be used as an alternative to the 'exit' event unless the intention is to schedule additional work.

process.on('beforeExit', (code) => {
  console.log('Process beforeExit event with code: ', code);
});

process.on('exit', (code) => {
  console.log('Process exit event with code: ', code);
});

console.log('This message is displayed first.');

// Prints:
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0