事件:'exit'
【Event: 'exit'】
code<integer>
'exit' 事件会在 Node.js 进程即将由于以下原因之一退出时触发:
【The 'exit' event is emitted when the Node.js process is about to exit as a
result of either:】
- 显式调用了
process.exit()方法; - Node.js 事件循环不再有任何其他工作要执行。
此时无法阻止事件循环退出,一旦所有 'exit' 监听器运行完毕,Node.js 进程将终止。
【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.】
监听器回调函数会使用由 process.exitCode 属性指定的退出代码,或者传递给 process.exit() 方法的 exitCode 参数来调用。
【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.】
import process from 'node:process';
process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});const process = require('node:process');
process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});监听器函数必须仅执行同步操作。Node.js 进程在调用 'exit' 事件监听器后会立即退出,这会导致事件循环中仍在排队的任何额外工作被放弃。例如,在以下示例中,超时将永远不会发生:
【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:】
import process from 'node:process';
process.on('exit', (code) => {
setTimeout(() => {
console.log('This will not run');
}, 0);
});const process = require('node:process');
process.on('exit', (code) => {
setTimeout(() => {
console.log('This will not run');
}, 0);
});