事件:'beforeExit'


【Event: 'beforeExit'

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

【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.】

监听器回调函数会被调用,并且将 process.exitCode 的值作为唯一参数传入。

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

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

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

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

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

import process from 'node:process';

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: 0const process = require('node:process');

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