#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 50 of 62hard

What is the Child Process module in Node.js?

Spawning and managing child processes.

What You'll Learn

  • Creating child processes
  • Different spawn methods
  • Communication between processes

Child Process Methods

MethodDescription
spawnLaunches a new process with streaming I/O
execSpawns shell, buffers output
execFileLike exec but without shell
forkSpawns Node.js process with IPC

spawn()

code.jsJavaScript
const { spawn } = require('child_process');

const ls = spawn('ls', ['-la']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

exec()

code.jsJavaScript
const { exec } = require('child_process');

exec('ls -la', (error, stdout, stderr) => {
  if (error) {
    console.error(`error: ${error.message}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
});

// With promises
const util = require('util');
const execPromise = util.promisify(exec);

const { stdout } = await execPromise('ls -la');

fork() - IPC Communication

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

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

child.send({ hello: 'world' });

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

// child.js
process.on('message', (msg) => {
  console.log('From parent:', msg);
  process.send({ reply: 'got it' });
});