In Node.js, what does child_process.fork add on top of spawn, and how do messages sent over its IPC channel behave?
answer
- a fresh Node process, not a clone
- send() meets 'message'
- JSON unless you opt in
- an open channel keeps processes alive
basics
~20 schild_process.fork starts a new Node.js process running a module, with its own memory and V8 instance, plus an IPC channel: send() and 'message' carry copies serialized as JSON by default, or by the v8 serializer when serialization is 'advanced'.
solid answer
~50 s`fork(modulePath)` spawns `process.execPath` with the parent's `execArgv` and adds an `'ipc'` entry to `stdio`. Nothing is cloned: the child loads the module from scratch in its own process, memory and V8 instance. The two sides talk through `subprocess.send()` and `process.send()`, received as `'message'` events. Every message is serialized and parsed, so the receiver gets a copy: with the default `serialization: 'json'`, `NaN` arrives as `null`, a `Map` or `Set` as `{}` and a `Date` as a string, while a `BigInt` makes `send()` throw. `'advanced'` uses the v8 serializer, which carries `Map`, `Set`, `BigInt`, `Buffer` and `Error`. `send()` returns `false` when the channel has closed or the backlog is too large, and you can pass a `net.Server` or `net.Socket` handle along with a message. An open channel keeps the parent alive until `disconnect()`, and keeps the child alive once it listens for `'message'`.
code
javascript · 16 linesimport { fork } from 'node:child_process';
import process from 'node:process';
if (process.argv[2] === 'child') {
process.on('message', (msg) => {
process.send({ echoed: msg });
process.disconnect(); // close the channel so the child can exit
});
} else {
const child = fork(import.meta.filename, ['child'], { serialization: 'advanced' });
child.on('message', (msg) => console.log(msg));
child.on('exit', (code) => console.log('child exited with', code));
child.send({ pages: new Map([[1, 'intro']]), size: 10n });
}
// { echoed: { pages: Map(1) { 1 => 'intro' }, size: 10n } }
// child exited with 0go deeper
Recall that fork runs a Node.js module in a new process and that send() and the 'message' event carry messages both ways.
Explain that messages are copies serialized as JSON by default, what 'advanced' adds, and why fork is not a clone of the parent.
Show you manage lifetime and flow control: disconnect(), the send() return value and callback, and what a child does when the parent dies.
Weigh a forked child's memory and per-message serialization cost against the crash isolation it buys before making it a service's pattern.
## What fork actually starts `child_process.fork(modulePath, args, options)` is a **special case of `spawn()`** for Node.js programs. It: - runs `process.execPath` (the current `node` binary, unless you pass `execPath`) with the parent's **`execArgv`** by default, then `modulePath` and `args`; - inherits the parent's stdin, stdout and stderr unless `silent: true` pipes them instead; - adds an **`'ipc'`** entry to `stdio`, which creates the message channel. A custom `stdio` array must contain exactly one `'ipc'` entry; leave it out and `fork()` throws `ERR_CHILD_PROCESS_IPC_REQUIRED`. Despite the name, it does **not** behave like the POSIX `fork(2)` call. Nothing is copied from the parent: no variables, no open connections, no module cache. The child starts a new V8 instance with its **own memory** and loads the module from scratch. Node's docs warn that because each child needs its own resources, spawning a large number of them is not recommended. That cost is the main thing separating this from the worker-threads material (threads inside one process) and from the cluster module, which builds on `fork()` to share a server port. ## The IPC channel - The parent sends with **`subprocess.send(message)`**; the child receives `process.on('message', ...)`. - The child sends with **`process.send(message)`**; the parent receives `subprocess.on('message', ...)`. In a process started without an IPC channel, `process.send` is `undefined`. - **`subprocess.disconnect()`** in the parent or **`process.disconnect()`** in the child closes the channel; both sides then see `'disconnect'`, and `subprocess.connected` and `process.connected` become `false`. - `send()` returns **`false`** when the channel has closed or when the backlog of unsent messages exceeds a threshold that makes sending more unwise. Its optional callback runs once the message is sent (not necessarily received) and is the documented hook for flow control. Without a callback, a failed send is reported as an `'error'` event. - A second argument can carry a **handle**: a `net.Server`, `net.Socket` or `dgram.Socket`, so the child can accept connections or take over one socket. Sending IPC sockets is not supported on Windows. - Messages whose `cmd` property starts with `NODE_` are reserved for Node's internal use and are not delivered as `'message'`. ## What survives serialization Every message is **serialized and parsed**: the receiver gets a copy, never a shared object. The `serialization` option picks the format: | Value sent | `'json'` (default) arrives as | `'advanced'` arrives as | |---|---|---| | `NaN` | `null` | `NaN` | | `new Map([[1, 'a']])` | `{}` | a `Map` | | `new Set(['a'])` | `{}` | a `Set` | | `new Date(0)` | the string `'1970-01-01T00:00:00.000Z'` | a `Date` | | `Buffer.from('hi')` | `{ type: 'Buffer', data: [104, 105] }` | a `Buffer` | | `new Error('x')` | `{}` | an `Error` | | `10n` | `send()` throws a `TypeError` | `10n` | `'advanced'` uses the `node:v8` serialization API, based on the HTML structured clone algorithm. Node's docs note two limits: it is **not a full superset of JSON** (properties set on objects of built-in types are not passed on), and its **performance may differ** from JSON depending on the shape of the data. Either way, the cost is paid twice per message: once to serialize in the sender and once to parse in the receiver. Large payloads sent often are a CPU and latency cost on both processes. ## Who keeps whom alive Lifetime is where forked children surprise people: 1. In the **parent**, an open channel keeps the event loop running. A parent that has finished its own work will not exit until the channel closes, unless you call `subprocess.channel.unref()` (and `subprocess.unref()` for the process itself). 2. In the **child**, Node starts the channel **unreferenced** until the child registers a `'message'` or `'disconnect'` listener. A child with no such listener can exit normally; one that listens for `'message'` stays up until the channel closes or it calls `process.exit()`. 3. Calling **`disconnect()`** on either side lets both processes exit once nothing else keeps them alive. 4. If the parent dies, its end of the channel closes and the child receives `'disconnect'`. A child holding other work, such as a listening server, keeps running unless it reacts to that event. ## Practical guidance - Use `fork()` when the child is your own Node.js code and you need **messages and crash isolation**; a child that crashes takes down only its own process. - Keep messages **small and plain**; send references (an ID, a file path) rather than whole documents. - Choose `'advanced'` only when you need its types, and make it the same on both sides by setting it at `fork()` time. - Always decide how a child ends: on `'disconnect'`, on an explicit shutdown message, or when the parent kills it.
- How do you avoid flooding a slow forked child with messages?Watch `subprocess.send()`'s return value and callback. It returns `false` when the backlog of unsent messages is too large, and the callback runs once each message has been sent, so you can wait for it before sending more. A request-reply protocol, where the child acknowledges each job, bounds the in-flight work more strictly.
- A forked child finished its job but the parent never exits. Why?The IPC channel is still open, and an open channel keeps the parent's event loop running. Call `subprocess.disconnect()` when you are done, have the child call `process.disconnect()` or exit, or call `subprocess.channel.unref()` if the parent should be free to exit while the channel stays open.
Two offices exchanging documents by courier: what arrives is a photocopy, never the original, and the plain-paper courier (JSON) cannot carry some kinds of item that the specialist courier ('advanced') can.
- fork() copies the parent's memory, so the child starts with the parent's variables.
- Objects passed to send() are shared by reference between parent and child.
- With the default serialization a Map arrives intact.
- A forked child listening for 'message' exits by itself when its work is done.
- send() returning true means the child has received the message.