'exit' 事件


当 Node.js 进程因以下原因之一即将退出时,则会触发 'exit' 事件:

  • 显式调用 process.exit() 方法;
  • Node.js 事件循环不再需要执行任何其他工作。

此时无法阻止退出事件循环,并且一旦所有 'exit' 事件的监听器都已完成运行时,Node.js 进程将终止。

使用 process.exitCode 属性指定的退出码或传给 process.exit() 方法的 exitCode 参数调用监听器回调函数。

process.on('exit', (code) => {
  console.log(`退出码: ${code}`);
});

监听器函数必须只执行同步操作。 在调用 'exit' 事件监听器之后,Node.js 进程将立即退出,从而导致在事件循环中仍排队的任何其他工作被放弃。 例如,在以下示例中,定时器中的操作不会发生:

process.on('exit', (code) => {
  setTimeout(() => {
    console.log('此处不会运行');
  }, 0);
});

The 'exit' event is emitted when the Node.js process is about to exit as a result of either:

  • The process.exit() method being called explicitly;
  • The Node.js event loop no longer having any additional work to perform.

There is no way to prevent the exiting of the event loop at this point, and once all 'exit' listeners have finished running the Node.js process will terminate.

The listener callback function is invoked with the exit code specified either by the process.exitCode property, or the exitCode argument passed to the process.exit() method.

process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});

Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur:

process.on('exit', (code) => {
  setTimeout(() => {
    console.log('This will not run');
  }, 0);
});