The child_process module provides the ability to spawn child processes, which is simply the ability to execute CMD commands.

const { spawn } = require('child_process');
const ls = spawn('ls'['-lh'.'/usr']);

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 exits, exit code${code}`);
});
Copy the code

By default, pipes for stdin, stdout, and stderr are set up between the parent Node.js process and its derived children. These pipes have limited (and platform-specific) capacity. If the child writes stdout beyond this limit and does not capture the output, the child blocks and waits for the pipe buffer to accept more data. This is the same behavior as pipes in the shell. If the output is not consumed, the {stdio: ‘ignore’} option is used.

If the options object has the options.env.PATH environment variable, use it to perform command lookups. Otherwise, process.env.path is used.

On Windows, environment variables are case insensitive. Node.js sorts env’s keys in lexicographical order, using the case-insensitive first key. Only the first entry (in lexicographical order) is passed to the subprocess. Problems can occur on Windows when objects passed to the env option have multiple variables with the same key name (such as PATH and PATH).

The child_process.spawn() method spawns child processes asynchronously and does not block the Node.js event loop. The child_process.spawnsync () function provides the equivalent functionality in a synchronous manner, but blocks the event loop until the spawned process exits or is terminated.

For convenience, the child_process module provides some synchronous and asynchronous alternatives to child_process.spawn() and child_process.spawnsync (). Each of these alternative methods is implemented based on child_process.spawn() or child_process.spawnsync ().

Child_process.exec (): Spawn the shell and run commands in the shell, passing stdout and stderr to the callback function when finished.

Child_process.execfile (): Similar to child_process.exec(), but by default it directly derives the command without first deriving the shell.

Child_process.fork (): Spawn a new Node.js process and invoke the specified module that has established the IPC communication channel and can send messages between the parent and child processes.

Child_process.execsync (): A synchronized version of child_process.exec() that blocks the Node.js event loop.

Child_process.execfilesync (): a synchronized version of child_process.execfile () that blocks the Node.js event loop.

For some use cases, such as automated shell scripts, a synchronous approach may be more convenient. But in most cases, the synchronous approach has a significant impact on performance because it suspends the event loop until the spawned process completes.

The close event

The ‘close’ event is emitted when the child’s STdio stream has been shut down. This is different from the ‘exit’ event because multiple processes may share the same STDIO stream.

const { spawn } = require('child_process');
const ls = spawn('ls'['-lh'.'/usr']);

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

ls.on('close'.(code) = > {
  console.log(The child process uses the code${code}Close all stdio ');
});

ls.on('exit'.(code) = > {
  console.log(The child process uses the code${code}Exit `);
});
Copy the code

Disconnect events

The ‘disconnect’ event is emitted after calling subprocess.disconnect() in the parent process or process.disconnect() in the child process. After disconnection, messages cannot be sent or received, and the subprocess. Connected property is false.

Error event

The ‘error’ event is raised whenever:

  1. Unable to spawn processes;

  2. Unable to kill processes

  3. Failed to send message to child process.

An ‘exit’ event may or may not fire after an error occurs. When listening for both ‘exit’ and ‘error’ events, you need to prevent the handler from being accidentally called multiple times.

The exit events

The ‘exit’ event is emitted when the child process terminates. If the process exits, code is the final exit code for the process, otherwise null. Signal is the string name of the signal if the process terminates because of a signal received, otherwise null. At least one of the two values is non-null.

The child’s STDIO stream may still be open when the ‘exit’ event is triggered.

Node.js sets up signal handlers for SIGINT and SIGTERM, and the Node.js process does not terminate immediately upon receiving these signals. Instead, Node.js will perform a series of cleanup operations and then upgrade the processed signal again.

Message event

The ‘message’ event is emitted when a child process sends a message using process.send().

Messages are delivered through serialization and parsing. The message received may not be exactly the same as the one originally sent.

If the serialization option is set to ‘advanced’ when spawning the child process, the message parameter can contain data that cannot be represented by JSON.

[Reference article] (nodejs.org/dist/latest…