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
广告