Process object in nodeJS
Introduction
- It is a global object
- It provides information about and control over the current NodeJS process
- It is always available to Node.js applications without using require() because its a global object
Process events
The process object is an instance of EventEmitter
- beforeExit
- disconnect
- exit
- message
- multipleResolves
- rejectionHandled
- uncaughtException
- uncaughtExceptionMonitor
- unhandledRejection
- warning
Event: beforeExit
The ‘beforeExit’ event is emitted when Node.js empties its event loop and has no additional work to schedule
process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); }); // output // Process beforeExit event with code: 0
Event: exit
- The ‘exit’ event is emitted in the following cases
- The process.exit() method being called explicitly
- The Node.js event loop no longer having any additional work to perform
process.on('exit', (code) => { console.log('About to exit with code:', code); });
Event: rejectionHandled
The ‘rejectionHandled’ event is emitted whenever a Promise has been rejected and an error handler was attached to it
process.on('uncaughtException', (err, origin) => { console.log('Caught exception:' err); console.log('Exception origin:' origin); }); setTimeout(() => { console.log('This will still run.'); }, 500); // Intentionally cause an exception, but don't catch it. funcWhichIsNotDefined(); console.log('This will not run.'); // Caught exception: ReferenceError: funcWhichIsNotDefined is not defined // Exception origin: uncaughtException // This will still run.
Event: rejectionHandled
Returns an array containing the command-line arguments passed
console.log('argv', process.argv); //node process.js param1=value1 param=value2