Node.js – beforeExit 事件
当 Node.js 清空事件循环并且没有其他工作要安排时,将触发 'beforeExit' 事件。当没有安排工作时,Node.js 进程正常退出,但在 'before exit' 事件上注册的侦听器可以执行异步调用,从而导致 Node.js 进程继续。
示例 1
创建一个名为 "beforeExit.js" 的文件,复制以下代码。创建文件后,使用命令 "node beforeExit.js" 运行此代码,如下例所示 −
// process 'beforeExit' Demo Example // Importing the process module const process = require('process'); // Calling the 'beforeExit' event process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); }); // Calling the 'exit' event process.on('exit', (code) => { console.log('Process exit event with code: ', code); }); // Printing the first message console.log('Hi... First Message !');
输出
Hi... First Message ! Process beforeExit event with code: 0 Process exit event with code: 0
示例 2
我们来看另一个示例。
// process 'beforeExit' Demo Example // Importing the process module const process = require('process'); // Editing the exit code process.exitCode = 100; // Calling the 'beforeExit' event process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); }); // Printing the first message console.log('Hi... First Message');
输出
Hi... First Message Process beforeExit event with code: 100
广告