0
0
NodejsHow-ToBeginner · 4 min read

How to Use fork in Node.js for Child Processes

In Node.js, you use fork from the child_process module to create a new Node.js process that runs a separate script. This allows you to run tasks in parallel and communicate between parent and child processes using messages.
📐

Syntax

The fork method is called from the child_process module and takes the path to a JavaScript file to run as a child process. It returns a ChildProcess object that you can use to communicate with the child.

  • child_process.fork(modulePath, args, options)
  • modulePath: Path to the child script file.
  • args: Optional array of string arguments passed to the child.
  • options: Optional settings like environment variables.
javascript
const { fork } = require('child_process');

const child = fork('childScript.js', ['arg1', 'arg2'], { env: { NODE_ENV: 'production' } });
💻

Example

This example shows how to create a child process using fork that runs a separate script. The parent sends a message to the child, and the child replies back. This demonstrates parallel execution and message passing.

javascript
// parent.js
const { fork } = require('child_process');

const child = fork('./child.js');

child.on('message', (msg) => {
  console.log('Message from child:', msg);
});

child.send({ greeting: 'Hello from parent' });

// child.js
process.on('message', (msg) => {
  console.log('Message from parent:', msg);
  process.send({ reply: 'Hello from child' });
});
Output
Message from parent: { greeting: 'Hello from parent' } Message from child: { reply: 'Hello from child' }
⚠️

Common Pitfalls

Common mistakes when using fork include:

  • Not handling messages properly, causing lost communication.
  • Forgetting to provide the correct path to the child script.
  • Assuming fork runs the same code as the parent; it runs a separate file.
  • Not listening for exit or error events on the child process.

Always handle communication and errors to avoid silent failures.

javascript
// Wrong: forgetting to listen for messages
const { fork } = require('child_process');
const child = fork('./child.js');
child.send({ hello: 'world' }); // No listener for child's reply

// Right: listen for messages and errors
child.on('message', (msg) => {
  console.log('Child says:', msg);
});
child.on('error', (err) => {
  console.error('Child error:', err);
});
📊

Quick Reference

Method/PropertyDescription
fork(modulePath, args, options)Creates a new Node.js child process running the specified script.
child.send(message)Sends a message to the child process.
child.on('message', callback)Listens for messages from the child process.
child.on('exit', callback)Detects when the child process exits.
child.on('error', callback)Handles errors from the child process.

Key Takeaways

Use child_process.fork to run a separate Node.js script as a child process.
Communicate between parent and child using the send and message events.
Always handle errors and exit events on child processes to avoid issues.
Provide the correct path to the child script when calling fork.
fork is useful for parallel tasks and offloading work from the main process.