'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);
});