Child Processes in Node.js

Spawning child processes have multiple advantages. In this blog, we will first try to understand the WHY behind child processes and then dive into an example snippet.

Why Child Processes?

Let’s try to understand the major benefits of spawning child processes.

  • Parent process can distribute tasks amongst child processes to be done in parallel. This will help in achieving the maximum out of the available CPU cores on your machine.
  • Child process is not able to access the memory of the parent process. This way, you can keep sensitive information, available in parent memory away from the child.
  • Environment variables can be selectively made available to the child process. This way, you can keep sensitive environment variables secret from the child.
  • While spawning child process, we can specify the system user and system user group for the child process. It helps in controlling the permissions which the child process will have.

child_process Module in Node

node:child_process module provides spawn method for creating a new child process. Let’s directly dive into an example showing how to spawn  a child process and listen to it’s events.

const { spawn } = require('node:child_process');
const fs = require('node:fs');

const logFileWriteStream = fs.createWriteStream('/tmp/workspace/log.log');
const errorFileWriteStream = fs.createWriteStream('/tmp/workspace/error.log');

const child = spawn(
	'find',
    ['/'],
    {
    	cwd: '/tmp/workspace',
      env: {
        PATH: process.env.PATH
      }
    }
);

child.stdout.pipe(logFileWriteStream);
child.stderr.pipe(errorFileWriteStream);

child.on('error', function(error) {
	console.log(`* Process error: ${error.message}`);
});

child.on('close', function(code) {
	console.log(`* Process close with code: ${code}`);
});

child.on('exit', function(code, signal) {
	if (code != null || code != undefined) {
  		console.log(`* Process exit with code: ${code}`);
	}
	if (signal != null || signal != undefined) {
		console.log(`* Process exit with signal: ${signal}`);
	}
});

Arguments to spawn Function

In the above snippet, we are spawning a child process which runs find command with single argument '/'. The first argument of the spawn function is the command which will be run in the child process. Second argument is the Array of arguments for the command. Third argument for spawn function is an options object. Let’s see some of the options one by one.

The current working directory is set using the cwd option. If not passed, child process will inherit it from parent.

The env option is used to set the environment variables for the child process. If not passed, all the environment variables of the parent process will be available to the child.

The output of the command is piped to log file write stream. The error of the command is piped to error file write stream.

Events on Child Process

error event is obtained in case of failure of spawning the child or in case of failure of killing the child. Error object is sent as argument to the callback of this event.

exit event is obtained when the child process exits. Exit code of the process and the signal by which the process was terminated are sent as arguments to the callback of this event.

close event is emitted after the child process has exited or failed to spawn. It also signifies that the stdin, stderr and stdout streams of the child process have been closed. Exit code is sent as argument to the callback of this event.


Kedar Chandrayan

Kedar Chandrayan

I focus on understanding the WHY of each requirement. Once this is clear, then HOW becomes easy. In my blogs too, I try to take the same approach.