Node.JS Child Process Creation

Since first tutorial of this series, we have been saying again and again that node.js applications are single threaded. In node.js multitasking is performed via events and callbacks. However, in addition to these features you can utilize CPU’s multiple cores by assigning the child processes. Yes, node.js contains child processes. In this and the following article we shall study node.js child process creation.

Child_process Module

Node.js child process creation involves using child_process module. There are three ways that can be used to create child processes via child_process module. They are as follows:

  • exec: This function runs in a shell or command prompt and stores output in a buffer.
  • spawn: This function creates a totally process via command prompt.
  • fork: It is a type of spawn function and is used to create new process as well.

Creating Child Process via exec

The syntax for creating child process via exec is simple. You have to use child_process.exec(command[, options], callback). Here first option is the command that you want to execute in the child process, it can be running some file etc. The second parameter is the set of options that you can pass to the process. We shall pass only integer which sets the id of the process. Finally, the third option is the callback function with three parameters: error, stdout, stderr. Take a look at the following example to understand how exec works.

First create a file named “child.js” and add the following line of code to it

const fileSystems = require('fs');
const cld_proc = require('child_process');

for(var i=1; i<=5; i++) {
   var parentproc = cld_proc.exec('node child.js '+i,function 
      (error, stdout, stderr) {
      if (error) {
         console.log('Error Code: '+error.code);
         console.log('Reason of error: '+error.signal);
      console.log('Stdout value: ' + stdout);
      console.log('Stderror value: ' + stderr);

   parentproc.on('exit', function (code) {
      console.log('Child process is exiting with exit code: '+code);

Download the code Try the code

Take a careful look at the above code. Here we use a for loop that executes five times. In each iteration we call child_process variables exec method. The first parameter is the command to run, here we pass the command to run the child.js file we created earlier. The second parameter is the id of the process while the third function is the callback. Inside the callback function, if error occurs during child process execution we print that. Else we print the output of the child process via stdout. Finally we print the code with which child process exited.

In the next article, we shall how to create child process via spawn and fork.

<<< Node.JS Path ModuleNode.JS Spawn-Fork Functions >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .