Process isolation
Split CPU-heavy or isolated application work into a separate Node.js process while retaining structured parent-child messaging.
Node.js · Function
child_process.fork() starts a new Node.js process to run a specified module and provides a built-in IPC channel for parent-child communication. It returns a ChildProcess instance.
fork() starts a new Node.js process to execute a specified module. It returns a ChildProcess with an IPC channel, allowing the parent and child to exchange messages; unlike the POSIX fork(2) call, it does not clone the current process.
child_process.fork(modulePath[, args][, options])| Name | Type | Description |
|---|---|---|
modulePath | string | URL | The module to run in the child. |
args | string[] | List of string arguments. |
options | Object | Options controlling the child process, including its working directory. |
A ChildProcess instance with an additional built-in IPC communication channel.
ChildProcess, which can be monitored and controlled using the child-process API.// parent.mjs
import { fork } from 'node:child_process';
const child = fork(new URL('./child.mjs', import.meta.url));
child.on('message', (message) => {
console.log(message);
child.disconnect();
});
// child.mjs
process.on('message', (message) => {
process.send?.({ result: message.value * 2 });
});
process.send?.({ result: 42 });The parent starts a separate Node.js process for the child module and receives data through the automatically established IPC channel.
Split CPU-heavy or isolated application work into a separate Node.js process while retaining structured parent-child messaging.
Create a dedicated child entry point that receives commands from a parent and returns results through IPC.
Run a Node.js module with a controlled child working directory and command-line arguments.
child_process.fork() do?It launches a new Node.js process for the specified module and returns a ChildProcess. The returned process includes an IPC channel for parent-child messaging.
Follow-up: How would you exchange data? Listen for message events in the parent and use the child process messaging APIs from the child to send values back.
fork() differ from spawn()?fork() is a specialized form of spawn() for starting Node.js processes. Its distinguishing feature is the built-in IPC communication channel.
Follow-up: When would spawn() be preferable? Use it when launching a general executable or when the specialized Node.js-module behavior and built-in IPC are not needed.
fork()?The first argument identifies the module that the child executes. Optional arguments are passed as strings, while options configure child-process behavior such as its working directory.
Follow-up: What should be checked when resolving the module? Ensure the module path or URL identifies the intended child entry point and that its runtime assumptions match the child process.
child_process.spawnChildProcesschild_process.execchild_process.execFilechild_process.execSync