Node.JS Spawn-Fork Functions

In the previous article we started our discussion about child processes in node.js. We know that there are three ways of creating a child process via node.js child_process module: exec, spawn and fork. In last article we saw a working example of exec function for creating and running child process. In this article we shall discuss Node.JS Spawn-Fork Functions for creating child processes.

Spawn

The command for creating a child process via spawn is this: child_process.spawn(command[, args][, options]). Here first option is the command that you want to execute in the child process, the second parameter is the list of arguments in the form of array. We shall pass the name of the file here that we want executed in a separate process. Finally the third 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. Take a look at the following example.

First create a file named “child.js” and add the following line of code to it
console.log(“Child process with id ” + process.argv[2] + ” completed execution.” );

The following is the code for parent.js file that contains parent function.

The spawn function relies on event rather than callback as was the case with exec. Whenever a child process completes execution the stdout eventEmitter generates data event which contains the output for the child process. In case of error the on event of stderror is generated and handled accordingly.

Fork

Fork is a type of spawn and is another way of generating child process in node.js.

The command for creating a child process via spawn is this: child_process.fork(modulePath[, args][, options]). Here first option is the path of the module that you want to execute. This is in string form. The first parameter is optional. The second parameter is the list of arguments in the form of array. We shall pass the name of the file here that we want executed in a separate process. Finally the third 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. Take a look at the following example.

First create a file named “child.js” and add the following line of code to it
console.log(“Child process with id ” + process.argv[2] + ” completed execution.” );

The following is the code for parent.js file that contains parent function for fork.