Node.js Process exit Event
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine.
The process.exit() method is the method that is used to end the Node.js process. Every process action on the machine or a program is an event. For every event, there is even a handler associated with the particular event that executes when we fire the particular event. To assign an event handler to the event we use the object.on() method in the node.js. In this article, we will discuss process exit event in Node.js
Syntax:
process.on("exit", callbackfunction)
Parameters: This method takes the following two parameters.
- exit: It is the name of the emit event in the process.
- callbackfunction: It is the event handler of the event.
Return Type: The return type of this method is void.
Example 1:
index.js
console.log( "Starting of the process" )
process.on( 'exit' ,() => {
console.log( "process.exit() method is fired" )
})
console.log( "Ending of the process" )
process.exit()
|
Run index.js file using below command:
node index.js
Output:
Starting of the process
Ending of the process
process.exit() method is fired
Example 2: Creating process exit event handler inside the user-defined event handler.
index.js
const events = require( "events" )
console.log( "Starting of the process" )
const eventEmitter = new events.EventEmitter()
ing event Handler
var Handler = function () {
process.on( 'exit' , () => {
console.log( "process.exit() method is fired" )
})
}
eventEmitter.on( "hello" ,Handler)
eventEmitter.emit( "hello" )
console.log( "Ending of the process" )
process.exit()
|
Run index.js file using below command:
node index.js
Output:
Starting of the process
Ending of the process
process.exit() method is fired
Reference:https://nodejs.org/api/process.html#process_event_exit
Last Updated :
30 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...