Node.js Child Process: Syntax, Methods, and Examples

Introduction

Node.js is widely used to build web applications, APIs, command-line tools, and background services. Sometimes, an application needs to perform tasks outside its main process, such as running a system command, executing another script, processing a file, or starting an external program.

Node.js provides the Child Process module to handle these tasks. It allows an application to create separate processes and execute commands without blocking the main application unnecessarily.

For example, a Node.js application can use a child process to run a Python script, execute a system command, or perform a time-consuming background task.

In this tutorial, you will learn what a Node.js child process is, its syntax, important methods, practical examples, common mistakes, and frequently asked interview questions.

What Is a Child Process in Node.js?

A child process in Node.js is a separate operating system process created by a parent process to execute a command, script, or program.

Node.js provides the built-in child_process module for creating and managing these processes. You do not need to install an external package to use it.

A child process runs independently of the parent process, with its own process ID and execution environment. Depending on the method used, the parent can receive the child’s output, send input, detect errors, and monitor when the process finishes.

Common use cases include:

  • Running operating system commands.
  • Executing Python, PHP, or other external scripts.
  • Performing CPU-intensive work in a separate process.
  • Processing files or generating reports.
  • Running background utilities and automation tasks.

Node.js provides four commonly used methods for creating child processes:

  1. exec() – Executes a command and collects its output.
  2. execFile() – Executes a program directly without using a shell by default.
  3. spawn() – Starts a process and streams its output.
  4. fork() – Starts another Node.js process with an additional communication channel.

Each method is useful for different situations.

Syntax of Node.js Child Process

First, import the required method from the built-in child_process module.


const { exec } = require('node:child_process');
The basic syntax of the exec() method is:
exec('command', (error, stdout, stderr) => {
    if (error) {
        console.error(error.message);
        return;
    }

    console.log(stdout);
});

Here:

  • command is the system command you want to execute.
  • error contains information about an execution failure.
  • stdout contains the command’s standard output.
  • stderr contains its standard error output.

The exact behavior depends on the method used. For example, spawn() provides streams for handling output as it arrives, while fork() is designed for communication between Node.js processes.

Example: Using Child Process in Node.js

Let’s execute a simple system command using the exec() method.

Example:


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

exec('node --version', (error, stdout, stderr) => {
    if (error) {
        console.error('Execution failed:', error.message);
        return;
    }

    if (stderr) {
        console.error('Command error output:', stderr);
    }

    console.log('Node.js Version:', stdout.trim());
});

Output:

Node.js Version: v22.x.x

The exact version depends on the Node.js installation.

Explanation:

  1. The child_process module is imported using require().
  2. The exec() method runs the node –version command.
  3. The callback receives the error, standard output, and standard error.
  4. If execution fails, the error is displayed.
  5. Otherwise, the Node.js version is printed to the console.

The exec() method collects the command’s output in memory. Therefore, it is suitable for commands with relatively small output. For large or continuous output, spawn() is generally a better choice.

Important Child Process Methods

Understanding the main methods helps you choose the right approach for your application.

1. exec()

The exec() method runs a command through a shell and collects its output.


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

exec('echo Hello from Node.js', (error, stdout) => {
    if (error) {
        console.error(error.message);
        return;
    }

    console.log(stdout.trim());
});

Use exec() for simple commands when the output is manageable. Avoid passing untrusted input into shell commands because this can introduce command-injection vulnerabilities.

2. execFile()

The execFile() method executes a specified program directly by default, without creating a shell.


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

execFile('node', ['--version'], (error, stdout) => {
    if (error) {
        console.error(error.message);
        return;
    }
    console.log(stdout.trim());
});

It is useful when you want to execute a program with separate command-line arguments. This approach avoids shell interpretation by default, although you must still validate inputs and choose executable paths carefully.

3. spawn()

The spawn() method starts a process and exposes its output through streams. It is particularly useful when a command produces large amounts of output or runs for a long time.


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

const child = spawn('node', ['--version']);

child.stdout.on('data', (data) => {
    console.log(data.toString());
});

child.on('error', (error) => {
    console.error('Failed to start:', error.message);
});

child.on('close', (code) => {
    console.log('Process closed with code:', code);
});

Unlike exec(), spawn() does not collect all output into a single string by default.

4. fork()

The fork() method starts a new Node.js process and establishes an IPC (inter-process communication) channel for exchanging messages.

Parent file (parent.js):


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

const child = fork('./child.js');

child.on('message', (message) => {
    console.log('Message from child:', message);
});

child.on('error', (error) => {
    console.error(error.message);
});

Child file (child.js):


process.send('Hello from child process');

When you run parent.js, the child sends a message to the parent, which prints it to the console.

Use fork() when you need separate Node.js execution and message-based communication.

Real-Life Example of Node.js Child Process

Consider an application that generates PDF reports for users. Generating a large report may take time and involve running an external utility.

Instead of collecting a large amount of command output in memory, the application can use spawn() to start a report-generation program and monitor its progress.


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

const report = spawn(
    'node',
    ['generate-report.js'],
    { stdio: 'inherit' }
);

report.on('error', (error) => {
    console.error('Unable to start report:', error.message);
});

report.on('close', (code) => {
    if (code === 0) {
        console.log('Report generated successfully');
    } else {
        console.error('Report generation failed');
    }
});

In this example, generate-report.js represents a script that performs the report-generation task. The stdio: ‘inherit’ option allows the child process to use the parent’s standard input, output, and error streams.

The parent application can continue handling other asynchronous operations while the child process runs. However, this does not automatically make the entire application faster; the benefit depends on the workload and how the task is implemented.

For production applications, you should also consider timeouts, cancellation, process monitoring, and error logging.

Common Mistakes When Using Child Process

Developers should avoid the following mistakes when working with Node.js child processes.

1. Using exec() for large output

The exec() method buffers output in memory and has a configurable maxBuffer limit. Large output can cause the command to fail. Use spawn() when output is large or continuous.

2. Ignoring errors

A child process may fail to start, or the command may exit unsuccessfully. Handle the error event and check the exit code or close event.

3. Passing untrusted input to shell commands

Using exec() with user-controlled input can expose your application to command injection. Prefer execFile() or spawn() with separate arguments and without shell execution when appropriate.

4. Assuming child processes share memory

Child processes have separate memory spaces. Use IPC, standard input/output, files, or another communication mechanism to exchange data.

5. Forgetting to manage long-running processes

An unnecessary child process can consume CPU and memory. Use suitable timeouts, terminate processes when appropriate, and handle their exit events.

Conclusion

The Node.js Child Process module allows applications to execute external commands, run separate scripts, and manage independent processes. Its main methods—exec(), execFile(), spawn(), and fork()—serve different purposes.

Use exec() for commands with manageable output, execFile() for direct program execution, spawn() for streaming output, and fork() for communication between Node.js processes.

By choosing the appropriate method, handling errors correctly, and avoiding unsafe shell commands, you can build more reliable and secure Node.js applications.

Node.js Child Process – Interview Questions

Q 1: What is API error handling in Node.js?
Ans: It is the process of detecting errors during API requests and returning appropriate responses and HTTP status codes.
Q 2: What is centralized error handling in Express.js?
Ans: It uses a common error-handling middleware to process errors from different routes.
Q 3: What does next(error) do?
Ans: It passes an error to Express.js error-handling middleware.
Q 4: What is the difference between 401 and 403?
Ans: 401 Unauthorized indicates missing or invalid authentication credentials. 403 Forbidden means the client does not have permission to perform the operation.
Q 5: Why should stack traces not be returned in production?
Ans: They may reveal internal application details that could create security risks.

Related Node.js Tutorials