In you want to execute a command line binary with Node.js. For even newer version of Node.js (v8.1.4), the events and calls are similar or identical to older versions, but it’s encouraged to use the standard newer language features. Examples:
For buffered, non-stream formatted output (you get it all at once), use child_process.exec
:
1 2 3 4 5 6 7 8 9 10 11 |
const { exec } = require('child_process'); exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => { if (err) { // node couldn't execute the command return; } // the *entire* stdout and stderr (buffered) console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); }); |
You can also use it with Promises:
1 2 3 4 5 6 7 8 9 |
const util = require('util'); const exec = util.promisify(require('child_process').exec); async function ls() { const { stdout, stderr } = await exec('ls'); console.log('stdout:', stdout); console.log('stderr:', stderr); } ls(); |
If you wish to receive the data gradually in chunks (output as a stream), use child_process.spawn
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const { spawn } = require('child_process'); const child = spawn('ls', ['-lh', '/usr']); // use child.stdout.setEncoding('utf8'); if you want text chunks child.stdout.on('data', (chunk) => { // data from standard output is here as buffers }); // since these are streams, you can pipe them elsewhere child.stderr.pipe(dest); child.on('close', (code) => { console.log(`child process exited with code ${code}`); }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.