Node.js Child Process

Node.js Child Process

The Node.js child_process module allows developers to spawn child processes, similar to the popen(3) system call in UNIX. This is useful when you need to execute system commands, run external scripts, or manage multiple Node.js processes simultaneously.

Introduction to Applied AI:–Click Here

There are three major ways to create a child process in Node.js:

Data Science Tutorial:-Click Here

  1. child_process.exec() – runs a command in a shell and buffers the output.
  2. child_process.spawn() – launches a new process with a given command, suitable for handling large data streams.
  3. child_process.fork() – a special case of spawn() designed for spawning Node.js processes with an additional communication channel.

1. Node.js child_process.exec() Method

The exec() method executes a shell command and buffers the entire output before returning it in the callback.

Syntax:

child_process.exec(command[, options], callback)

Parameters:

  • command: The command string to execute.
  • options (optional):
    • cwd: Current working directory of the child process.
    • env: Environment key-value pairs.
    • encoding: Output encoding (default: utf8).
    • shell: Shell to execute with (/bin/sh on UNIX, cmd.exe on Windows).
    • timeout: Time in ms before the process is killed (default: 0).
    • maxBuffer: Maximum output buffer (default: 200*1024).
    • killSignal: Kill signal to terminate the process (default: SIGTERM).
    • uid/gid: Set user and group identity of the process.
  • callback: Invoked with (error, stdout, stderr) after process termination.

Download New Real Time Projects :–Click here

Example 1 – Running a Batch File

child_process_example1.js

const exec = require('child_process').exec;

exec('my.bat', (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});

my.bat

dir
mkdir child

Running node child_process_example1.js will list directory contents (dir) and create a new folder (child). On Linux/macOS, replace dir with ls.

Machine Learning Tutorial:–Click Here

Example 2 – Multiple Child Processes

support.js

console.log("Child Process " + process.argv[2] + " executed.");

master.js

const child_process = require('child_process');

for (let i = 0; i < 3; i++) {
  let workerProcess = child_process.exec('node support.js ' + i, (error, stdout, stderr) => {
    if (error) {
      console.log(error.stack);
      console.log('Error code: ' + error.code);
      console.log('Signal received: ' + error.signal);
    }
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
  });

  workerProcess.on('exit', (code) => {
    console.log('Child process exited with exit code ' + code);
  });
}

Running node master.js will execute support.js three times, each with different arguments.

Complete Advance AI topics:- CLICK HERE

2. Node.js child_process.spawn() Method

The spawn() method launches a process and returns streams (stdout & stderr). Unlike exec(), it does not buffer the output, making it suitable for processes generating large data.

Syntax:

child_process.spawn(command[, args][, options])

Parameters:

  • command: The command to run.
  • args: Array of string arguments.
  • options: Similar to exec(), including cwd, env, stdio, uid, gid, etc.

Example – Using spawn()

support.js

console.log("Child Process " + process.argv[2] + " executed.");

master.js

const child_process = require('child_process');

for (let i = 0; i < 3; i++) {
  let workerProcess = child_process.spawn('node', ['support.js', i]);

  workerProcess.stdout.on('data', (data) => {
    console.log('stdout: ' + data);
  });

  workerProcess.stderr.on('data', (data) => {
    console.log('stderr: ' + data);
  });

  workerProcess.on('close', (code) => {
    console.log('child process exited with code ' + code);
  });
}

Run node master.js to see each child process print its execution message.

Deep Learning Tutorial:– Click Here

3. Node.js child_process.fork() Method

The fork() method is a specialized version of spawn() for creating Node.js processes. It includes a built-in communication channel (process.send() and process.on('message')).

Syntax:

child_process.fork(modulePath[, args][, options])

Parameters:

  • modulePath: Path to the module executed in the child.
  • args: Array of string arguments.
  • options: Includes cwd, env, execPath, execArgv, silent, uid, gid, etc.

Example – Using fork()

support.js

console.log("Child process " + process.argv[2] + " executed.");

master.js

const child_process = require('child_process');

for (let i = 0; i < 3; i++) {
  let workerProcess = child_process.fork('support.js', [i]);

  workerProcess.on('close', (code) => {
    console.log('child process exited with code ' + code);
  });
}

Running node master.js spawns three child processes using fork().

Complete Python Course with Advance topics:-Click Here
SQL Tutorial :–Click Here

✔️ With these three methods—exec(), spawn(), and fork()—Node.js gives developers powerful tools to manage external processes and scale applications efficiently.


nodejs child process example node js child process vs worker thread child process npm node.js spawn nodejs spawn vs exec child process spawn node child process exec execsync nodejs node js child process w3schools node js child process tutorial node js spawn nodejs child process, nodejs child processes, node.js child process, child process node.js, exec child process node.js, fork child process node.js, spawn child process node.js, node.js child process tutorial, node.js child process examples, child process events node.js, child process management node.js, child process communication node.js, node child process, performance child process node.js, child process error handling node.js, stub child process in node js, handling child processes node.js, child process

Share this content:

Post Comment