Node.js – Process beforeExit Event

Node.jsServer Side ProgrammingProgramming

The 'beforeExit' event is called when Node.js empties its event loop and has no other work to schedule. The Node.js process exits normally when there is no work scheduled but a listener registered on the 'before exit' event can make async calls and thereby cause the Node.js process to continue.

Example 1

Create a file with the name "beforeExit.js" and copy the following code. After creating the file, use the command "node beforeExit.js" to run this code as shown in the example below −

// process 'beforeExit' Demo Example

// Importing the process module
const process = require('process');

// Calling the 'beforeExit' event
process.on('beforeExit', (code) => {
   console.log('Process beforeExit event with code: ', code);
});

// Calling the 'exit' event
process.on('exit', (code) => {
   console.log('Process exit event with code: ', code);
});

// Printing the first message
console.log('Hi... First Message !');

Output

Hi... First Message !
Process beforeExit event with code: 0
Process exit event with code: 0

Example 2

Let's take a look at one more example.

// process 'beforeExit' Demo Example

// Importing the process module
const process = require('process');

// Editing the exit code
process.exitCode = 100;

// Calling the 'beforeExit' event
process.on('beforeExit', (code) => {
   console.log('Process beforeExit event with code: ', code);
});

// Printing the first message
console.log('Hi... First Message');

Output

Hi... First Message
Process beforeExit event with code: 100
raja
Updated on 24-Nov-2021 06:42:59

Advertisements