Node.js 进程退出事件
进程是Node.js中的全局对象,用于跟踪和包含正在机器上执行的特定Node.js进程的所有信息。
process.exit()方法用于结束Node.js进程。机器上的每个进程操作或程序都是一个事件。对于每个事件,都有一个特定事件相关的处理程序,当我们触发特定事件时执行。要为事件分配事件处理程序,我们在Node.js中使用object.on()方法。在本文中,我们将讨论Node.js中的进程退出事件。
语法:
process.on("exit", callbackfunction)
参数:
该方法接受以下两个参数。
- exit: 它是进程中发出的事件的名称。
- callbackfunction: 它是该事件的事件处理程序。
返回类型:
该方法的返回类型为void。
示例1:
index.js
console.log("Starting of the process")
// Binding the event to the eventhandler
process.on('exit',() => {
console.log("process.exit() method is fired")
})
console.log("Ending of the process")
// Exiting the process
process.exit()
使用以下命令运行 index.js 文件:
node index.js
输出:
Starting of the process
Ending of the process
process.exit() method is fired
示例2: 在用户定义的事件处理程序内创建进程退出事件处理程序。
index.js
// Importing events object
const events = require("events")
console.log("Starting of the process")
const eventEmitter = new events.EventEmitter()
// Initializing
ing event Handler
var Handler = function() {
// Event handler of exit event
process.on('exit', () => {
console.log("process.exit() method is fired")
})
}
// Bind the user defined event
eventEmitter.on("hello",Handler)
// Emit the event
eventEmitter.emit("hello")
console.log("Ending of the process")
// Exiting the process
process.exit()
使用以下命令运行 index.js 文件:
node index.js
输出:
Starting of the process
Ending of the process
process.exit() method is fired
参考 : https://nodejs.org/api/process.html#process_event_exit