The Child Process Module: A Brief Introduction

umair nehri
RIXED_LABS
Published in
7 min readFeb 28, 2021

Introduction

In this blog, we shall be discussing the child_process module present in Node.js. But before we begin let’s first understand what exactly Node.js is.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine which gives users the ability to execute their javascript code outside a browser. It can be used for writing command-line based programs, for server-side scripting in case of web applications and even for developing Discord bots!

The Child Process Module

Node.js applications execute their code as a single Operating System process running on a single CPU meaning that it would work in a single-threaded mode, which can be ideal for light-weight applications.

But with increasing code/features, the overall load by your application can be a problem even in the case of powerful host machines. This issue can be solved by using parallel processing in the case of multi-core CPU machines.

Child process is basically a subprocess that is created by a parent process which in our case runs the application. These child processes can communicate with each other with the help of a messaging system.

Node.js has a child_process module for dealing with the creation of these subprocesses and the module can be used by the developers for even interacting with the host Operating System through running shell commands.

There are three main methods present in the module which could be used for the creation of these processes namely spawn, exec and fork. Let us discuss all of these in detail!

spawn() method

The spawn() method will create a new process with a command. It has the following syntax:

child_process.spawn(command[, args][, options])

Here,
Command specifies the command to run in a string format
Args specifies the list of arguments to be passed to the command in an array format
Options specifies one of the many options available for this method like:
• cwd [string] which is the current working directory of the child process
• env [object]
which is the environment key-value pairs.
• stdio [array] which is the child’s stdio configuration
customFds [array] which is the file descriptors for the child to use for studio
detached [boolean] which prepares child to run independently of its parent process
uid [number] which sets the user identity of the process
gid [number] which sets the group identity of the process

This method returns streams (stdout and stderr) and the application would start getting the response streams as soon as the process starts executing when the program is executed.

Example

Let us look over an example to understand how this method works,

[Image showing a code snippet to explain the spawn() method]

In the above code, we have first imported the spawn() command from the child_process module, then we have declared a constant mv that will execute the mv command on our system which is basically used for moving files and directories from one location to the other. The stdout will basically capture the output stream which basically carries the output of the command once it is executed on the system and display it after “stdout:”. If our command is executed but errors are thrown in the error stream, stderr will capture it and display it after “stderr:”. Once the command is successfully executed, data is transferred through the streams and the process is closed the last function will display the message saying that the child process has exited with the x code.

exec() method

The exec() method is used to create child processes that can be used for executing commands on the operating system. It creates a shell process on the system which can be used for executing commands. It has the following syntax:

child_process.exec(command[, options][, callback])

Here,
Command [string] specifies the command to run, we can provide space-separated arguments here
Options [object] specifies one of the many options available for this method like:
• cwd [string] which is the current working directory of the child process
• env [object]
which is the environment key-value pairs
• encoding[string] which is for the encoding, default is “utf8”
shell [string] which sets the shell to execute the command with. '/bin/sh’on Unix, process.env.ComSpec on Windows
maxBuffer [number] which sets the largest amount of data in bytes allowed on stdout or stderr
uid [number] which sets the user identity of the process
gid [number] which sets the group identity of the process
Callback [function] is a function that is called with the output when the process is terminated, it gets three arguments namely error [error], stdout [string/buffer], stderr [string/buffer]

The exec() method saves the output of the command when it is executed in a buffer in the memory which can be accepted through a callback function passed into the exec() function.

Example

Let us look over an example to understand how this method works,

[Image showing a code snippet to explain the exec() method]

In the above code, we have first imported the exec() command from the child_process module, then we have passed the first argument to it which should be in a string format and in our case we used ls -la which will list all files and folders with all of their entries using a long listing format. In the second argument, we have passed three parameters namely error, stdout and stderr. The error argument will capture any errors which would be a result due to the failure of execution of the command, this could be because the shell used for running the command couldn’t find it. The stdout argument will be capturing the standard output stream which will read the output once the command is successfully executed. The stderr argument will capture any errors being sent to the standard error stream after the command’s execution.

In the callback function, the first if condition will look for any errors and if there are any, it will display the error message using console.error() and finally exit that conditional statement. The second if condition will look for any error messages printed after the command’s execution and display it using console.error(). Else if the command is successfully executed with no error messages, we finally display its output using console.log(`stdout:\n${stdout}`);

fork() method

The fork() method is a special case of the spawn() method in which a child process can directly communicate with the parent process which runs our program with the help of send(). It has the following syntax:

child_process.fork(modulePath[, args][, options])

Here,
modulePath [string] specifies the module to run in the child
args [string[]] specifies an array list of arguments in string form
Options specifies one of the many options available for this method like:
• cwd [string] which is the current working directory of the child process
• env [object]
which is the environment key-value pairs.
• stdio [array] which is the child’s stdio configuration
serialization [string] which specifies the kind of serialization to be used for sending messages between the processes, possible values here are ‘json’ and ‘advanced’ although it is set to ‘json’ by default.
detached [boolean] which prepares child to run independently of its parent process
uid [number] which sets the user identity of the process
gid [number] which sets the group identity of the process

The main difference between fork() and spawn() is that fork() allows the establishment of a communication channel between the parent and child process when we use the fork() method thus enabling us to share messages back and forth between the two processes.

Example

Let us look over an example to understand how this method works,

[Image showing a code snippet to explain the fork() method]

Here we basically have two files namely Index.js and Childprocess.js respectively.
In our first file, we have first imported the fork() command from the child_process module, then we have forked the childprocess.js file which will be executed with the node command. Then we have the message event which will listen to any messages coming from the child process and then show it in the output using console.log() and finally, we are using send() for sending the message1 to the child process.
In our second file, we have another message event which will be listening for any messages coming from the parent process and displaying it using console.log and finally, we are using send() for sending the message2 to the parent process.

This is how the output would look once we execute the index.js file using the node command. Since we are exchanging as well as listening to messages in both the files we have the output as we were expecting it to be.

Conclusion

This brings us to the end of this introductory blog regarding the child process module of Node.js. It was made to give the audience an overview regarding the module and If you’d like to know more about the module you should definitely check out the official documentation page of Nodejs.

Blog by Nerd of AX1AL. Join us at the discord server.

--

--