Node.js child_process Module

Java FileNode.js built-in modules


Node.js is a single-threaded JavaScript runtime environment, but sometimes we need to execute system commands or run other programs. In such cases, we need to use thechild_processmodule.

child_processThe module allows Node.js applications to create child processes, which can execute system commands, run other scripts or programs, and communicate with the parent process.


Why do we need child_process?

  1. Execute system commands: For example, executingls、gitand other command-line tools
  2. Run CPU-intensive tasks: Avoid blocking the Node.js main thread
  3. Interact with programs written in other languages: For example, calling Python or C++ programs
  4. Improve application performance: Fully utilize multi-core CPUs through multi-process

Four methods for creating child processes

1. exec() - Execute simple commands

exec()The method is used to execute simple shell commands and buffer the output results.

Example

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

exec('ls -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`Execution error: ${error}`);
    return;
  }
  console.log(`Standard output:\n${stdout}`);
  if (stderr) {
    console.error(`Standard error output:\n${stderr}`);
  }
});

Features:

  • Suitable for executing simple commands
  • Returns the complete buffered output
  • Has a maximum buffer limit (default 200KB)

2. execFile() - Execute executable files

execFile()Similar toexec(), but directly executes the file instead of going through the shell.

Example

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

execFile('node', ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});

Features:

  • Compareexec()More secure (does not go through the shell)
  • Higher execution efficiency
  • Cannot use shell features (such as pipes, wildcards, etc.)

3. spawn() - Stream processing of child processes

spawn()The method uses a streaming interface to handle the input/output of child processes.

Example

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

const ls = spawn('ls', ['-lh', '/usr']);

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

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

ls.on('close', (code) => {
  console.log(`Child process exit code: ${code}`);
});

Features:

  • Suitable for handling large amounts of output
  • Streaming processing, high memory efficiency
  • Can process output in real time

4. fork() - Create Node.js child processes

fork()Yesspawn()A special case of , specifically used to create new Node.js processes.

Example

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

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

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

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

Features:

  • Creates a new Node.js instance
  • Built-in IPC (inter-process communication) channel
  • Suitable for CPU-intensive tasks

Inter-process communication (IPC)

Parent and child processes can communicate throughsend()andmessageevents.

Parent process (parent.js):

Example

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

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

child.send({ parent: 'Hello from parent' });

Child process (child.js):

Example

process.on('message', (msg) => {
  console.log('Child process received:', msg);
  process.send({ child: 'Hello from child' });
});

Error handling

Properly handling child process errors is very important:

Example

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

child.on('error', (err) => {
  console.error('Failed to start child process:', err);
});

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

child.on('exit', (code, signal) => {
  if (code) console.log(`Child process exit code: ${code}`);
  if (signal) console.log(`Child process terminated by signal: ${signal}`);
});

Best practices

  1. Security: Avoid passing user input directly to child processes
  2. Resource management: Clean up completed child processes in a timely manner
  3. Error handling: Always handle error events and exit events
  4. Performance considerations: For frequently created child processes, consider using a process pool
  5. Cross-platform compatibility: Pay attention to command differences across different operating systems

Summary

child_processThe module is the core module in Node.js for handling child processes, providing four methods for creating child processes:

  1. exec()- Suitable for simple commands
  2. execFile()- Suitable for executing executable files
  3. spawn()- Suitable for streaming processing
  4. fork()- Suitable for creating Node.js child processes

Choose the appropriate method based on specific needs, and pay attention to error handling and resource management to fully leverage Node.js's multi-process capabilities.

Java FileNode.js built-in modules

Other extensions