Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 133 ยท Processes and Threads

Child Processes

Run other programs from Node.js with child_process. Learn spawn, exec, execFile and fork, stdio streams, exit codes, killing children, IPC messages and avoiding shell injection.

Sometimes your Node.js program needs help from another program: a command-line tool such as git or ffmpeg, a script written in another language, or a second copy of Node running a risky or heavy task. The node:child_process module lets you start another process, give it input, read its output, listen for its exit and stop it when needed.

A child process is a completely separate program with its own memory and its own event loop. That isolation is its biggest strength: if the child crashes, your parent program survives. It is also its cost: starting a process takes tens of milliseconds and communicating means copying data. In this lesson you will learn the four ways to start a child (spawn, exec, execFile, fork), how to talk to it through standard streams and IPC messages, how to stop it, and how to avoid the most famous security hole in this module.

In our editor you can start Node itself with process.execPath (the path of the running node binary). Other programs such as git are not installed in the sandbox, so examples that need them are shown read-only. We never print process IDs or timings, because they differ on every run.

The four ways to start a process

Function Starts Output Uses a shell? Best for
spawn(cmd, args) any program streams (stdout, stderr) no (by default) long-running programs, large output
execFile(cmd, args) any program buffered, delivered at the end no short commands with small output
exec(commandLine) a shell command line buffered, delivered at the end yes quick one-liners with pipes (trusted text only)
fork(modulePath) a Node.js script streams + an IPC channel no talking to another Node program

Each also has a synchronous twin (spawnSync, execFileSync, execSync) that blocks the whole event loop until the child ends. They are fine in a start-up script or build tool, and wrong inside a server handling requests.

execFile: run a command, get the result

The simplest case: run a program, wait for it to finish, and read what it printed. execFile buffers the output for you. Its callback style becomes a promise with util.promisify (see The util Module).

Node.js Run Node as a child with execFile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

stdout is a string with the trailing newline kept (hence the JSON.stringify to make it visible). The arguments travel as an array, so there is no quoting problem: each element reaches the child as exactly one argument, even if it contains spaces.

By default the child inherits your environment variables. Passing env replaces them entirely, which is also a good way to avoid leaking secrets such as API keys into a child you do not fully trust.

When the child fails

If the child exits with a non-zero code, the promise rejects. The error object carries everything you need to diagnose it.

Node.js Handling a failing child

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the two different meanings of err.code. For a program that ran and returned a failure, it is the exit code (a number: 0 is success, anything else is failure). For a program that could not be started at all, it is a system error string such as ENOENT ("no such file or directory"; see Errors and Error Handling). Check typeof err.code before you interpret it.

spawn: streaming output

execFile and exec hold all output in memory and refuse to continue past a limit (maxBuffer, 1 MiB by default). For long-running or chatty programs, spawn gives you the output as it happens as streams, the same readable streams you met in Streams Fundamentals.

Node.js Streaming child output with spawn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Every child has three standard streams, exposed by default as pipes: child.stdin (writable, the child reads it), child.stdout and child.stderr (readable). The chunks you receive are not line-aligned (three console.log calls may arrive as one chunk or three), so the example wraps stdout in readline, which delivers complete lines.

exit versus close

Two events announce the end, and the difference matters:

  • 'exit' fires when the process ends. Its stdio streams may still hold unread data.
  • 'close' fires after the process ended and all its stdio streams have closed. This is the event to wait for if you want complete output.

The values are (code, signal). A normal end gives a code and signal is null; a process killed by a signal gives code as null and the signal name, such as 'SIGTERM'.

The error event: a classic crash

If the command cannot be started, spawn does not throw. It emits an 'error' event on the child object. Like every EventEmitter, an 'error' event with no listener becomes an uncaught exception. This program is missing the listener:

Node.js spawn without an error listener (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The process crashes with Error: spawn this-program-does-not-exist ENOENT and a note that the error was emitted on the ChildProcess instance. The fix is a one-liner: always attach child.on('error', ...), or await once(child, 'spawn')/'close' inside a try/catch (the once helper rejects if 'error' fires first).

Feeding the child through stdin

child.stdin is a writable stream, so you can send data to a program that reads standard input, exactly as a shell pipe would. Here a child reads text, upper-cases it, and writes it back. We use the same technique as Transform streams, but the transformer runs in another process.

Node.js Piping data into a child process

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Forgetting child.stdin.end() is the most common reason a spawned program "hangs": the child waits for more input forever. Remember that a child that reads stdin cannot finish until you close it.

If the child may exit early, writing to a closed stdin raises an EPIPE error, so attach child.stdin.on('error', ...) in production code.

stdio options

The stdio option decides what each of the three streams connects to. The common settings:

  • 'pipe' (default): a stream object on the parent side.
  • 'inherit': share the parent's stream, so the child's output appears directly where yours does. Ideal for build tools and CLIs that just run another command.
  • 'ignore': connect to nothing, discarding the output.
NODE
// Read-only: typical for a CLI wrapper on your own machine
import { spawn } from 'node:child_process';

const child = spawn('git', ['status', '--short'], { stdio: 'inherit' });
child.on('close', (code) => process.exit(code ?? 1));

The shell and the injection trap

exec (and spawn with { shell: true }) hands a string to a shell such as /bin/sh. The shell interprets special characters: ;, &&, |, $(), backticks, > and more. That is convenient for a one-off pipeline and dangerous when any part of the string comes from a user. This is called command injection, and it lets an attacker run any command your process is allowed to run.

Node.js Command injection with exec, and the safe version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With exec the shell saw the ; and ran a second command. With execFile the whole string arrived as one harmless argument.

Rules for safe child processes: prefer execFile/spawn with an argument array; never build a command line by string concatenation with user input; if you must use a shell, pass user values through the environment (env) and refer to them as shell variables, or validate them against a strict allow-list. Also remember that arguments beginning with - can be read as options by the program: use -- before untrusted file names where the tool supports it.

fork: a Node child with a message channel

fork(path) starts a new Node.js process running a script and opens an IPC channel (inter-process communication) between parent and child. You send values with send() and receive them in 'message' events. The values are copied using the structured clone algorithm, so objects, arrays, Maps, Dates and BigInt work, but functions do not.

In a real project the child is a separate file. Our editor has one file, so the script forks itself, deciding which role to play from its arguments. import.meta.filename is the path of the running file.

Node.js Parent and child talking over IPC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The child keeps running as long as the IPC channel is open, because an open channel is something the event loop waits for. That is why the parent sends a stop message and the child calls process.disconnect(). Messages are delivered in order.

Use fork when you want a Node program to supervise another one: isolating plug-in code, running a job in a separate crash domain, or restarting a worker that leaks memory. For heavy computation inside one program, worker threads are cheaper to start and can share memory. For serving HTTP across several CPU cores, see Cluster, Scaling and Load Balancing.

Stopping a child

A process you start is your responsibility. Orphaned children keep running (and keep your parent alive if you wait for them). The tools:

  • child.kill() sends SIGTERM, a polite request to stop. child.kill('SIGKILL') cannot be ignored and gives the child no chance to clean up.
  • The timeout option on exec/execFile/spawn kills the child with killSignal if it runs too long.
  • The signal option accepts an AbortSignal, which fits the cancellation patterns of AbortController and Cancellation.
Node.js Timeouts, kill and AbortSignal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A child can ignore SIGTERM if it installs a handler (a well-behaved server uses it to shut down gracefully; see The process Object), so production supervisors send SIGTERM, wait a grace period, then escalate to SIGKILL. Killing a process does not automatically kill its children: a shell started by exec can leave grandchildren running.

Output limits and large data

exec and execFile reject with ERR_CHILD_PROCESS_STDIO_MAXBUFFER when a child prints more than maxBuffer bytes (default 1 MiB) and then kill it. If you expect a lot of output, use spawn and process the streams, or raise the limit consciously. Never read unbounded output into memory in a server.

Choosing between child processes, workers and cluster

Need Use
Run an existing command-line tool spawn / execFile
Run a one-line shell pipeline you wrote yourself exec (trusted text only)
Isolated Node script with messaging fork
CPU-heavy JavaScript with shared memory worker_threads
One HTTP server across many CPU cores cluster (built on fork)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function is the safest way to run a program with a user-supplied argument?

    An argument array never goes through a shell, so characters such as ; or | stay plain data. Strings given to exec or a shell are interpreted as commands.
  2. 2. What is the difference between the child's 'exit' and 'close' events?

    exit announces that the process ended. close waits until all stdio streams are closed too, so all output has been delivered.
  3. 3. What happens if spawn() cannot find the program and you attached no 'error' listener?

    spawn reports start failures through an 'error' event on the child object, and an unhandled error event is thrown like any EventEmitter error.
  4. 4. A child process that reads stdin never finishes in your test. What is the most likely cause?

    A program that reads until end of input waits for the end signal. Closing child.stdin tells it no more data will come.
  5. 5. What does a fork()ed child need to receive messages from its parent?

    fork opens an IPC channel. The child receives messages with process.on('message') and replies with process.send().

Summary

  • spawn streams output, execFile buffers it, exec runs a command line through a shell, and fork starts a Node script with a message channel.
  • Use argument arrays (execFile, spawn) for untrusted values. exec and shell: true open the door to command injection.
  • Wait for 'close' for complete output; read (code, signal); handle 'error' for programs that fail to start; end child.stdin when the child reads input.
  • Stop children with kill(), timeout or an AbortSignal, and prefer SIGTERM before SIGKILL.
  • exec/execFile have a maxBuffer; use spawn for large output.
  • Child processes are isolated and heavier than threads; pick workers for CPU work inside one program.

Next: Worker Threads