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

更新日期: 24-11-2021

583 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

入門
廣告
© . All rights reserved.