Node.js – process ‘exit’ Event


An ‘exit’ event is emitted when the process is going to exit due to the following reasons −

  • Process.exit() method is called explicitly.

  • The node event loop no longer have any task to perform.

Syntax

Event: 'exit'

Example 1

Create a file "exit.js" and copy the following code snippet. After creating the file, use the command "node exit.js" to run this code.

// 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()

Output

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

Example 2

Let’s take a look at one more example.

// 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()

Output

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

Updated on: 29-Oct-2021

526 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements