To run a command in a shell, in which you required buffered output (i.e. it is not a stream), use child_process.exec
. For example, if you wanted to run the command cat *.js file | wc -l
, with no options, that would look like this:
const exec = require('child_process').exec;
exec('cat *.js file | wc -l', (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
The function accepts up to three parameters:
child_process.exec(command[, options][, callback]);
The command parameter is a string, and is required, while the options object and callback are both optional. If no options object is specified, then exec
will use the following as a default:
{
encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null
}
The options object also supports a shell
parameter, which is by default /bin/sh
on UNIX and cmd.exe
on Windows, a uid
option for setting the user identity of the process, and a gid
option for the group identity.
The callback, which is called when the command is done executing, is called with the three arguments (err, stdout, stderr)
. If the command executes successfully, err
will be null
, otherwise it will be an instance of Error
, with err.code
being the exit code of the process and err.signal
being the signal that was sent to terminate it.
The stdout
and stderr
arguments are the output of the command. It is decoded with the encoding specified in the options object (default: string
), but can otherwise be returned as a Buffer
object.
There also exists a synchronous version of exec
, which is execSync
. The synchronous version does not take a callback, and will return stdout
instead of an instance of ChildProcess
. If the synchronous version encounters an error, it will throw and halt your program. It looks like this:
const execSync = require('child_process').execSync;
const stdout = execSync('cat *.js file | wc -l');
console.log(`stdout: ${stdout}`);