Visit us on www.bitwisebranding.com for Branding, Digital Marketing and Design Solutions.

How to create a child process in NodeJS

H
By Anuja Agrawal In NodeJS
In this blog, we will discuss how to create child process in NodeJS and how we can handle different events. We can easily create a child process using child_process module and these child processes can communicate with each other with a messaging system.

There are four different ways to create a child process in NodeJS:



In this article, we will be covering the fork() method of creating child process.

The fork() function:
This method of creating child process also creates a communication channel, so we can use the send function on the forked process along with the global process object itself to exchange messages between parent and forked process.

Let’s first create a child file. I am naming it as WorkerThread.js. In this file, we will write logic that we want to execute in separate thread or process.



There are other events that you can handle that best suits your requirement.

Now, let’s create our parent file – app.js. Here, we fork the WorkerThread.js and then we listen for the message event.



Now start the node server using below command.
1.node app.js

When you run this command you should get the following output.



In the app.js file above, it will send the Initialize WorkerThread message to be printed by the WorkerThread child process. We can send messages to parent process from forked child process in the similar way.

We need to listen for message event in parent process (app.js)



Now, we can use process.send() from forked child process to send message.

So, in this article we learnt the basic usage of fork() method of creating the child process and how communication channel can be used to exchange messages between parent and child process.

Reference: https://nodejs.org/api/child_process.html

Thanks for reading. Happy Coding……

Leave us a comment