0
0
Node.jsframework~5 mins

Why child processes are needed in Node.js

Choose your learning style9 modes available
Introduction

Child processes let Node.js run multiple tasks at the same time. This helps when one task takes a long time and you don't want to stop everything else.

When you need to run a heavy calculation without freezing your app.
When you want to run a separate program or script from your Node.js code.
When you want to handle multiple tasks in parallel to speed up work.
When you want to keep your main app responsive while doing background jobs.
Syntax
Node.js
const { fork } = require('child_process');

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

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

child.send('Hello child');

fork() creates a new Node.js process to run a separate script.

You can send messages back and forth between the main and child processes.

Examples
Use exec to run a shell command and get its output.
Node.js
const { exec } = require('child_process');

exec('ls -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  console.log(`Output:\n${stdout}`);
});
spawn runs a command and streams its output live.
Node.js
const { spawn } = require('child_process');

const child = spawn('node', ['script.js']);

child.stdout.on('data', (data) => {
  console.log(`Child output: ${data}`);
});
fork creates a child Node.js process that can communicate with the parent.
Node.js
const { fork } = require('child_process');

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

child.send({ task: 'start' });

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

This program creates a child process that runs worker.js. It sends a message to start work and listens for replies. This keeps the main app free to do other things.

Node.js
const { fork } = require('child_process');

// Fork a child process to run worker.js
const child = fork('./worker.js');

// Send a message to the child
child.send('Start work');

// Listen for messages from the child
child.on('message', (msg) => {
  console.log('Message from child:', msg);
});
OutputSuccess
Important Notes

Child processes run independently, so if one crashes, it won't crash the main app.

Use child processes to improve app speed and responsiveness.

Summary

Child processes let Node.js do many things at once.

They keep your app from freezing during heavy tasks.

You can send messages between main and child processes easily.