Node.js Process beforeExit Event
The ‘beforeExit’ is an event of class Process within the process module which is emitted when Node.js empties its event loop and has no additional work to schedule.
Syntax:
Event: 'beforeExit'
Parameters: This event does not accept any argument as the parameter.
Return Value: This event returns nothing but a callback function for further operation.
Example 1:
index.js
// Node.js program to demonstrate the // Process 'beforeExit' Event // Importing process module const process = require( 'process' ); // Event 'beforeExit' process.on( 'beforeExit' , (code) => { console.log( 'Process beforeExit event with code: ' , code); }); // Event 'exit' process.on( 'exit' , (code) => { console.log( 'Process exit event with code: ' , code); }); // Display the first message console.log( 'This message is displayed first.' ); |
Run the index.js file using the following command:
node index.js
Output:
This message is displayed first. Process beforeExit event with code: 0 Process exit event with code: 0
Example 2:
index.js
// Node.js program to demonstrate the // Process 'beforeExit' Event // Importing process module const process = require( 'process' ); // Updating the exit code process.exitCode = 100; // Event 'beforeExit' process.on( 'beforeExit' , (code) => { console.log( 'Process beforeExit event with code: ' , code); }); // Display the first message console.log( 'This message is displayed first.' ); |
Run the index.js file using the following command:
node index.js
Output:
This message is displayed first. Process beforeExit event with code: 100
Reference: https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_beforeexit