Nodejs-process Module

Abhishek N
5 min readJun 10, 2021

What is Nodejs Process Module?

The Node.js process model differs from traditional web servers in that Node.js runs in a single process with requests being processed on a single thread. One advantage of this is that Node.js requires far fewer resources. When a request comes in, it will be placed in an event queue. Node.js uses an event loop to listen for events to be raised for an asynchronous job. The event loop continuously runs, receiving requests from the event queue. Without wasting time lets deep dive into Process module.

Process Module is globally exposed in nodejs runtime we can directly access without importing the module. If we want we can import module using require as shown below.

const process = require('process');

Process module exposed some of the Api’s which we will be used to build the powerful application we will deep dive into explanation required and most used ones lets begin now.

Process Events

Process module exposes some of the events which has their own responsibility which listed below.

  1. beforeExit.
  2. disconnect.
  3. exit.
  4. message.
  5. multipleResolves.
  6. unhandledRejection.
  7. uncaughtException.
  8. warning.

lets discuss each with explanation.

1. beforeExit

This event is emitted when Node.js empties its event loop and has no additional work to schedule. this event can be used schedule any additional work before destroying the process . lets have small example.

const x = 10;
const y = 10;
function sum(a, b) {
return a + b;
}
console.log(`sum of ${x} and ${y} is`, sum(x, y));
process.on('beforeExit', (code) => {
console.log("process before exit event with code ", code)
})

The output of the above code is as shown below.

as you see the listener got executed ,the above listener will not be executed if process.exit() called or during any uncaught exception lets try that with below code.

const x = 10;
const y = 10;
function sum(a, b) {
process.exit()
return a + b;}
console.log(`sum of ${x} and ${y} is`, sum(x, y));
process.on('beforeExit', (code) => {
console.log("process before exit event with code ", code)
})

For the above code no output will be printed to console because we are manually exiting with process.exit().lets raise exception and try with below code.

const x = 10;
const y = 10;
function sum(a, b) {
throw 1;
return a + b;
}
console.log(`sum of ${x} and ${y} is`, sum(x, y));
process.on('beforeExit', (code) => {
console.log("process before exit event with code ", code)})

above code also will not execute the listener function.

2. disconnect

process disconnect event will help to disconnect(close the IPC channel) the child process when no longer needed lets have below example .if you don’t know what is child process go through the documentation or else wait for some days I was going write article on that in up coming days.

*Parent Processconst{fork}=require('child_process');
const child=fork('./child.js');
child.send("Hey child ,Iam parent");
child.disconnect();
*Child Processprocess.on("message", (message) => {
console.log(message);
});
process.on("disconnect", (messag) => {
console.log("Parent Disconnected with me");
});
Note* Both the child process and parent process code should be in seperate js file

The output of the above code is.

As you are seeing disconnect listener in child got called as soon as disconnect event emitted from the parent. after disconnect if the parent tries to send any message that will not be sent and exception will be thrown with message channel closed.

3. exit

Lets take the above example and alter the above code to achieve these .

*Parent Process
const { fork } = require('child_process');
const child = fork('child.js');
child.send("First Message from parent");
child.send("Second Message from parent");
*Child Process
process.on('message',(message)=>{
console.log(message);
process.exit();})
Note* Both the child process and parent process code should be in seperate js file

As you are seeing above parent sent two messages to the child but in child process .In child we are calling exit event after receiving first message so next message from the parent will not be captured from parent. lets listen for exit event in the child process with the below code.

*Child Processprocess.on('message',(message)=>{
console.log(message);
process.exit();})
process.on('exit',()=>{
console.log("child process exited");
})

the output of the above code is shown below

As you are seeing above after Process.exit() called. exit listener got executed. If there is any asynchronous stuff happening inside listener function that will be ignored. i.e listener function should always be synchronous.

4. message

I think you already familiar with what is message event does if you have covered all the points above. we can able to listen to message events by using below code.

process.on("message",(message)=>{
console.log(message);
})

5. multipleResolves

This is useful for tracking potential errors in an application while using the Promise constructor, as multiple resolutions are silently swallowed. However, the occurrence of this event does not necessarily indicate an error. For example, Promise.race() can trigger a 'multipleResolves' event.

This event will be triggered when any of the below event occur

  1. Resolved more than once.
  2. Rejected more than once.
  3. Rejected after Resolve.
  4. Resolved after Reject.

Below We example for the above conditions

*Resolved more than once new Promise((resolve, reject) => {
resolve('First call');
resolve('Swallowed resolve');
});
*Rejected more than once.new Promise((resolve, reject) => {
reject('First call');
reject('Swallowed reject');
});
*Rejected after Resolvenew Promise((resolve, reject) => {
resolve('First call');
reject('Swallowed reject');
});
*Resolved after Rejectnew Promise((resolve, reject) => {
reject('Swallowed reject');
resolve('First call');
});

These type of potential error can be captured using multipleResolves event using the below code.

process.on('multipleResolves', (type, promise, reason) => {
console.error(type, promise, reason);
});

6. unHandledRejection

Say you have big project upfront running and you forgot to handle promise rejection and this may lead to potential error inside application and now you need to track the unhandled rejection and you need to know what went wrong.you can handle this scenario with the unHandledRejection event as shown in the below code.

new Promise((resolve,reject)=>{
reject("something went wrong")
})
process.on('unhandledRejection',(err)=>{
console.log("Rejection unHandled",err);})

7. uncaughtException

In some of the cases we will not handle exception and we trust our code but when the code hits production there may be chances of exception for that particular block of code and sometime our application will stop running due to these errors.we can handle these type of potential errors using uncaughtException event by running the below code.

process.on('uncaughtException', (err) => {
console.log("Exception unHandled", err);
})
function fun() {
throw "Something went wrong"}
fun();

8. warning

A process warning is similar to an error in that it describes exceptional conditions that are being brought to the user’s attention. However, warnings are not part of the normal Node.js and JavaScript error handling flow. Node.js can emit warnings whenever it detects bad coding practices that could lead to sub-optimal application performance, bugs, or security vulnerabilities.

process.on('warning', (warning) => {
console.warn(warning.name);
console.warn(warning.message);
console.warn(warning.stack);
});

--

--

Abhishek N

Abhishek is a Software developer who is passionate about learning technology related stuff and implementing it in real world.