Node.js 处理 beforeExit 事件
'beforeExit'是 process 模块中的 Process 类的事件,当 Node.js 清空其事件循环并且没有额外的工作要安排时发出。
句法:
Event: 'beforeExit'
参数:此事件不接受任何参数作为参数。
返回值:此事件只返回一个回调函数以供进一步操作。
示例 1:
index.js
// Node.js program to demonstrate the
// Process 'beforeExit' Event
// Importing process module
const process = require('process');
// Event 'beforeExit'
process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code: ', code);
});
// Event 'exit'
process.on('exit', (code) => {
console.log('Process exit event with code: ', code);
});
// Display the first message
console.log('This message is displayed first.');
index.js
// Node.js program to demonstrate the
// Process 'beforeExit' Event
// Importing process module
const process = require('process');
// Updating the exit code
process.exitCode = 100;
// Event 'beforeExit'
process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code: ', code);
});
// Display the first message
console.log('This message is displayed first.');
使用以下命令运行index.js文件:
node index.js
输出:
This message is displayed first.
Process beforeExit event with code: 0
Process exit event with code: 0
示例 2:
index.js
// Node.js program to demonstrate the
// Process 'beforeExit' Event
// Importing process module
const process = require('process');
// Updating the exit code
process.exitCode = 100;
// Event 'beforeExit'
process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code: ', code);
});
// Display the first message
console.log('This message is displayed first.');
使用以下命令运行index.js文件:
node index.js
输出:
This message is displayed first.
Process beforeExit event with code: 100
参考: https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_beforeexit