Subprocess Communication With IPC
Send messages between a parent Node.js process and a forked child over the IPC channel, pick a serializer, match replies to requests and shut down cleanly.

Most people reach for child_process.spawn() and then parse whatever the child prints to stdout. It works until the child logs a warning on the same stream, or a message contains a line break, or you need to send an object and not a string. Node.js has a better channel for talking to a child that is also a Node.js program: the IPC channel that fork() opens for you. Messages are objects, they arrive whole, and the two sides use the same two calls: send() and a message event. This post covers how that channel works in Node.js 24 and 26, which values survive the trip, how to match replies to requests, and what the channel does when one side goes away. Every sample shows its output. If you also need to handle the text streams of a process, read process.stdin in Node.js explained alongside this one.
What IPC means here
IPC stands for inter-process communication. On Linux and macOS the channel is a Unix domain socket, and on Windows it is a named pipe, but you never see either. fork() creates it, and the child process documentation describes the two ends: the parent gets subprocess.send() and a message event on the ChildProcess object, and the child gets process.send() and a message event on process.
The channel exists only when the child is started with an ipc entry in its stdio option. fork() adds it automatically. spawn() does not, unless you ask for it by listing "ipc" in stdio, and only a Node.js child will do anything useful with it, because the other end has to speak the same serialization.
Two details matter for everything else. First, a message is delivered as a single unit, so you never reassemble chunks the way you do with a stream. Second, the channel keeps the parent and the child alive: as long as a message listener is attached on a connected channel, the event loop has a reason to stay open. That is why a worker that listens for messages does not exit by itself, and why closing the channel is how you stop it.
A first round trip
The smallest useful program is one parent, one child and one request. The parent forks the child, sends it a task and prints the reply.
import { fork } from "node:child_process";
const child = fork(new URL("./child.mjs", import.meta.url));
child.on("message", (msg) => {
console.log("parent got", msg);
child.disconnect();
});
child.on("exit", (code) => {
console.log("child exited with", code);
});
child.send({ task: "sum", numbers: [1, 2, 3] });process.on("message", (msg) => {
const result = msg.numbers.reduce((total, n) => total + n, 0);
process.send({ result });
});parent got { result: 6 }
child exited with 0fork() accepts a path or a URL, so new URL("./child.mjs", import.meta.url) finds the file next to the parent no matter which directory you start from. A bare string like "./child.mjs" is resolved against the current working directory instead, which is a common cause of a child that cannot be found when a script is launched from somewhere else.
The child never calls process.exit(). The parent calls child.disconnect() once it has its answer, the child sees its channel close, and with nothing left to wait on it exits with code 0. If you skip the disconnect, the program hangs forever with a healthy but idle child, which is the first mistake almost everyone makes with this API. The alternative is child.kill(), which sends SIGTERM and gives an exit code of null with a signal name, so prefer disconnect() when the child can finish by itself.
What can travel through the channel
By default the channel serializes messages with JSON. That has a consequence people discover late: anything JSON cannot express either disappears or changes shape on the way. A Map becomes an empty object, a Date becomes a string, undefined properties vanish and a BigInt throws.
The serialization option on fork() switches to "advanced", which uses the same structured clone algorithm as structuredClone() and postMessage(). It carries Map, Set, Date, typed arrays, BigInt and circular references. The next sample sends the same Map through both modes and asks the child what it received.
import { fork } from "node:child_process";
function ask(serialization) {
return new Promise((resolve) => {
const child = fork(new URL("./typeof-child.mjs", import.meta.url), [], {
serialization,
});
child.once("message", (answer) => {
child.disconnect();
resolve(answer);
});
child.send(new Map([["a", 1]]));
});
}
console.log("json:", await ask("json"));
console.log("advanced:", await ask("advanced"));process.on("message", (msg) => {
process.send(Object.prototype.toString.call(msg));
});json: [object Object]
advanced: [object Map]With "json" the child receives {}, which is what JSON.stringify(new Map([["a", 1]])) produces. With "advanced" it receives a real Map. The setting has to be the same on both ends, and since fork() passes it to the child for you, you only choose it once, in the parent.
Neither mode can send functions, class instances with methods, sockets or open file handles as plain data. Instances arrive as plain objects without their prototype. There is a narrow exception: send() takes an optional second argument, a handle such as a net.Server or net.Socket, which is how the cluster module hands connections to workers. Treat that as a special case and not a way to share objects.
Matching replies to requests
A single message listener on each side is fine for one question. The moment a parent asks the same child several things at once, replies can arrive in any order, and nothing in the channel tells you which answer belongs to which question. The standard fix is an id on every request that the child echoes back.
import { fork } from "node:child_process";
const child = fork(new URL("./rpc-child.mjs", import.meta.url));
const pending = new Map();
let nextId = 1;
child.on("message", ({ id, result }) => {
pending.get(id)(result);
pending.delete(id);
});
function call(n, delay) {
return new Promise((resolve) => {
const id = nextId++;
pending.set(id, resolve);
child.send({ id, n, delay });
});
}
const slow = call(5, 50).then((r) => console.log("slow done", r));
const fast = call(10, 10).then((r) => console.log("fast done", r));
await Promise.all([slow, fast]);
child.disconnect();process.on("message", ({ id, n, delay }) => {
setTimeout(() => process.send({ id, result: n * 2 }), delay);
});fast done 20
slow done 10The first request was sent first and finished last, because the child waited 50 ms before answering it and 10 ms before answering the second. Without the id, the promise for the first call would have been resolved with 20. The pending map is the whole mechanism: store the resolver, look it up on the way back, delete it. In a real program, add a timeout for each entry, and reject every pending promise when the child exits, otherwise a crashed child leaves callers waiting forever.
This is the same shape as a tiny RPC layer, and it is where a message queue or a worker pool library earns its keep once you have more than a couple of message types. Under that threshold, forty lines like these are easier to debug than a dependency.
Errors, exit and a closed channel
Four events and one property describe the life of the channel on the parent side.
messagefires for each incoming message.disconnectfires when either side closes the channel, andchild.connectedbecomesfalse.exitfires when the child process ends, with a code or a signal.errorfires if the process could not be spawned or killed, or ifsend()failed.
Calling send() on a closed channel does not throw synchronously. It emits an error event with code ERR_IPC_CHANNEL_CLOSED, or passes the error to the optional callback you give as the last argument. Either handle it, or check child.connected first. An unhandled error event on a ChildProcess crashes the parent.
The child gets the mirror image. process.connected tells it whether a parent is still there, and process.on("disconnect") fires when the parent goes away. A long-lived worker should listen for it and exit, because a child whose parent was killed with SIGKILL has no other way to learn that nobody is listening. We have seen orphaned workers sit at 100 percent of a core for days after a deploy for exactly this reason: the parent was restarted, the old children had no disconnect handler, and the supervisor never knew about them.
Also remember that process.send is undefined in a process that was not started with a channel. A script that runs both standalone and as a forked child should check if (process.send) before it calls it.
IPC or worker threads
worker_threads also passes messages with postMessage(), and the two APIs look alike. The difference is isolation. A forked child is a full process with its own memory, its own crash boundary and its own environment, at the cost of a startup that loads a whole Node.js runtime. A worker thread shares the process and can share memory through SharedArrayBuffer, starts faster, and dies with the process if something goes wrong in native code.
| Need | Better fit |
|---|---|
| Run CPU work without blocking the event loop | worker_threads |
| Contain a crash or a memory leak | fork() |
| Run with a different environment, user or working directory | fork() |
| Share a large buffer without copying | worker_threads |
| Run a separate program that happens to be Node.js | fork() |
If the child is not a Node.js program, IPC is the wrong tool. Use stdout and stderr with a line-based or JSON-lines protocol, which the next topic in the series, stdin, stdout and stderr in Node.js CLIs, covers.


