Node.js - 程序“退出”事件


由於以下原因,程序在退出時將發出“退出”事件 −

  • 顯式呼叫了 Process.exit() 方法。

  • 節點事件迴圈不再有任何任務要執行。

語法

Event: 'exit'

示例 1

建立一個檔案 “exit.js” 並複製以下程式碼片段。建立檔案後,使用命令 “node exit.js” 執行此程式碼。

// Process 'Exit' event Demo Example
console.log("Process Starts")

// Binding this event to the handler
process.on('exit',() => {
   console.log("process.exit() method is called")
})

console.log("Process Ends")

// Exiting the process
process.exit()

輸出

Process Starts
Process Ends
process.exit() method is called

示例 2

讓我們看另外一個示例。

// Proxess 'Exit' event Demo Example

// Importing the event module
const events = require("events")

console.log("Process Starts...")
const eventEmitter = new events.EventEmitter()

// Initializing the event Handler
var Handler = function() {
// Calling the exit event
process.on('exit', () => {
   console.log("process.exit() method is called")
})
}

// Calling the hello event
eventEmitter.on("hello", Handler)

// Emitting the event
eventEmitter.emit("hello")
console.log("Process Ends...")

// Exiting the process
process.exit()

輸出

Process Starts...
Process Ends...
process.exit() method is called

更新於:2021 年 10 月 29 日

643 次瀏覽

開啟你的 職業生涯

完成課程認證

開始進行
廣告
© . All rights reserved.