What is child_process?
The 'child_process' module in Node.js allows you to spawn new processes, execute commands, and communicate with those processes. It provides a way to run shell commands, scripts, and other programs from within a Node.js application.
What are child_process's main functionalities?
Spawning a new process
The 'spawn' function launches a new process with a given command. In this example, it runs the 'ls' command with the '-lh' and '/usr' arguments. The stdout and stderr streams are used to handle the output and errors, respectively.
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 exited with code ${code}`);
});
Executing a command
The 'exec' function runs a command in a shell and buffers the output. This example executes the 'ls -lh /usr' command and logs the stdout and stderr outputs. If an error occurs, it is logged as well.
const { exec } = require('child_process');
exec('ls -lh /usr', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
Forking a new Node.js process
The 'fork' function is a special case of 'spawn' used to create new Node.js processes. It allows for communication between the parent and child processes using the 'message' event. In this example, a new Node.js process is created to run 'child.js', and messages are exchanged between the parent and child.
const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', (msg) => {
console.log('Message from child', msg);
});
child.send({ hello: 'world' });
Other packages similar to child_process
execa
Execa is a modern alternative to 'child_process'. It provides a more user-friendly API for executing shell commands and handling their output. Execa supports promises, better error handling, and more features compared to the standard 'child_process' module.
cross-spawn
Cross-spawn is a package that provides a consistent API for spawning child processes across different platforms. It addresses issues with the default 'child_process' module, especially on Windows, making it easier to write cross-platform code.
shelljs
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. It provides a higher-level API for executing shell commands and scripts, making it easier to work with the filesystem and other shell tasks.
Security holding package
This package name is not currently in use, but was formerly occupied
by another package. To avoid malicious use, npm is hanging on to the
package name, but loosely, and we'll probably give it to you if you
want it.
You may adopt this package by contacting support@npmjs.com and
requesting the name.