Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท child_process, worker_threads and cluster

Node.js child_process.fork() method

Reference for child_process.fork() in Node.js: start another Node.js script as a child process with a built-in IPC channel, pass arguments, serialization and options.

child_process.fork() starts a new Node.js process that runs a script you name, and connects the two processes with a message channel. The parent calls child.send(value), the child receives it with process.on('message', ...), and the reverse works the same way. Messages are copied, not shared.

It is a special case of child_process.spawn(): the executable is always the current Node binary (process.execPath), and an extra IPC pipe is opened next to stdin, stdout and stderr. Each fork is a full Node.js instance with its own memory and event loop, so it is heavier than a worker thread but isolated from crashes in the parent.

NODE
import { fork } from 'node:child_process';

const child = fork('worker.js', ['--fast'], { silent: true });
child.send({ task: 'hello' });
child.on('message', (reply) => console.log(reply));

Try it

Node.js Talking to a forked 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.

Node.js Silent output and the execArgv option

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.

Syntax

NODE
child_process.fork(modulePath[, args][, options])
// returns ChildProcess
Name Description
modulePath Path or file: URL of the script to run in the child. Relative paths resolve against the parent's cwd (or options.cwd).
args Array of string arguments, available as process.argv.slice(2) in the child.
options.cwd Working directory of the child.
options.env Environment variables. Defaults to process.env.
options.execPath Use a different Node binary instead of process.execPath.
options.execArgv Flags passed to the Node binary itself. Defaults to the parent's process.execArgv.
options.silent If true, the child's stdin, stdout and stderr are piped to the parent. If false (the default) they are inherited.
options.stdio Full control over descriptors. It must contain exactly one 'ipc' entry, for example ['pipe', 'pipe', 'pipe', 'ipc']. Overrides silent.
options.serialization 'json' (default) or 'advanced' for the structured clone algorithm (supports Map, Set, BigInt, typed arrays).
options.signal An AbortSignal that kills the child when aborted.
options.timeout Milliseconds after which the child is killed with killSignal.
options.detached, uid, gid, killSignal Same meaning as for spawn().

Returns: a ChildProcess with send(), disconnect(), connected and the message and disconnect events.

Errors and edge cases: a missing script does not throw in the parent; the child starts, fails with Cannot find module and exits with code 1. A stdio array without 'ipc' throws ERR_CHILD_PROCESS_IPC_REQUIRED synchronously, and one with two 'ipc' entries throws ERR_IPC_ONE_PIPE.

Usage notes

  • The child keeps the parent alive. An open IPC channel is a reference on the event loop in both processes. Call child.disconnect() (or process.disconnect() in the child), or child.unref() after disconnecting, when the conversation is finished.
  • Default serialization is JSON. Functions, undefined properties, Map, Set and BigInt do not survive (sending a BigInt throws a TypeError). Use serialization: 'advanced' for richer values.
  • Messages are asynchronous and copied. Large payloads are slow; for big data prefer a file, a pipe, or shared memory in a worker thread.
  • Flags are inherited. The child gets the parent's process.execArgv, so --inspect in the parent would make the child try to use the same debug port. Override execArgv when that matters.
  • send() only exists with an IPC channel. In the child, process.send is undefined when the script was started any other way, so guard code that may run both ways.
  • Several children, one machine. Each fork costs tens of megabytes and tens of milliseconds to start. For many short tasks use a pool, or worker_threads instead.
  • Passing handles. child.send(message, sendHandle) can pass a TCP server or socket to the child. That is how the cluster module shares a listening port.
  • Not a shell. Arguments are passed as an array; there is no shell parsing, so the injection concerns of exec() do not apply to args.