'exit' 事件


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

  • 调用 process.exit()
  • Node.js 事件循环不再有额外的工作。

没有任何方法可以阻止事件循环的结束,当所有的 'exit' 事件监听器执行完成时,Node.js 进程就会终止。

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

'exit' 事件监听器的回调函数只允许同步操作。 'exit' 事件监听器被调用后,Nodje.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);
});