Skip to main content

Command Palette

Search for a command to run...

What is fork in node JS?

Updated
1 min read
What is fork in node JS?

In Node.js, the child_process module provides the fork() method, which allows you to create a new child process. It is a special case of the spawn() method, which is used to create a new process. The fork() method is similar to the spawn() method, but it runs in a separate process and communicates with the parent process using inter-process communication (IPC).

Here is an example of using the fork() method to create a new child process:

const { fork } = require('node:child_process');
const child = fork('child.js');

child.on('message', (message) => {
  console.log(`Received message from child: ${message}`);
});

child.send('Hello from the parent!');

The child.js file would look like this:

process.on('message', (message) => {
  console.log(`Received message from parent: ${message}`);
  process.send('Hello from the child!');
});

The fork() method is useful for running multiple instances of an application or for running long-running processes in the background. It allows you to take advantage of multiple CPU cores by creating child processes that can run concurrently.

More from this blog

R

Raja Muhammad Asher - Senior Software Engineer - Full Stack Developer

157 posts

Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, ExpressJS, MySQL, MongoDB. Love collaborating & making a difference