How to create child processes in Nodejs

How to create child processes in Nodejs

Table of contents

No heading

No headings in the article.

In Node.js, you can use the child_process module to create child processes that can execute JavaScript files or system commands. Here's an example of how to use the child_process.fork() method to create a child process:

const { fork } = require('child_process');

// Create a child process 
const child = fork('./child.js');

// Send a message to the child process 
child.send({ message: 'Hello from the parent process!' });

// Listen for messages from the child process 
child.on('message', (message) => { console.log(Received a message from the child: ${message}); });

This code creates a child process by calling the fork() method and passing in the path to the JavaScript file that the child process should execute. It then sends a message to the child process using the send() method and listens for messages from the child process using the on() method.

Here's an example of the child.js the file that the child process executes:

// Listen for messages from the parent process 
process.on('message', (message) => { 
console.log(Received message from parent: ${message});

// Send a message back to the parent process 
process.send({ message: 'Hello from the child process!' }); 

});

This code listens for messages from the parent process using the on() method and sends a message back to the parent process using the send() method.

You can also use the child_process.spawn() method to create a child process and execute a system command. Here's an example of how to use spawn():

const { spawn } = require('child_process');

// Create a child process and execute a system command
const child = spawn('ls', ['-lh', '/usr']);

// Listen for data events to print the output of the command
child.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

// Listen for error events to print any errors
child.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

// Listen for the close event to know when the process has finished
child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

This code creates a child process and executes the Ls command with the -LH and /usr arguments. It then listens for data events to print the output of the command, error events to print any errors, and the close event to know when the process has finished.

I hope these examples give you a good idea of how to use the child_process module to create child processes in Node.js.