Node.js › Child Processes & Process Management
How does inter-process communication (IPC) work between a parent process and a child created with fork()?
IntermediateAnswer
fork() automatically establishes a communication channel between the parent and child, letting both sides send and receive JSON-serializable messages via process.send() (in the child) or child.send() (in the parent), and listen via the 'message' event -- this is a much simpler communication mechanism than what's available with spawn() or exec(), which only expose the child's stdout/stderr/stdin streams rather than a structured message channel.
// parent.js
const { fork } = require('node:child_process');
const child = fork('./child.js');
child.send({ command: 'start', data: [1, 2, 3] });
child.on('message', (msg) => console.log('From child:', msg));
// child.js
process.on('message', (msg) => {
const result = msg.data.reduce((a, b) => a + b, 0);
process.send({ result });
});Real-world example A CPU-intensive report-generation task is offloaded to a forked child process, with the parent sending the report parameters via child.send() and receiving the completed report data back via the 'message' event, keeping the main process's event loop free to handle other requests throughout.