Node.js Process 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 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