I am in the process of porting a CLI library from Ruby over to Node.js. In my code I execute several third party binaries when necessary. I am not sure how best to accomplis
v13.9.0, LTS v12.16.1, and v10.19.0 --- Mar 2020Async method (Unix):
'use strict';
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.log( `stderr: ${data}` );
} );
ls.on( 'close', code => {
console.log( `child process exited with code ${code}` );
} );
Async method (Windows):
'use strict';
const { spawn } = require( 'child_process' );
const dir = spawn('cmd', ['/c', 'dir'])
dir.stdout.on( 'data', data => console.log( `stdout: ${data}` ) );
dir.stderr.on( 'data', data => console.log( `stderr: ${data}` ) );
dir.on( 'close', code => console.log( `child process exited with code ${code}` ) );
Sync:
'use strict';
const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );
console.log( `stderr: ${ls.stderr.toString()}` );
console.log( `stdout: ${ls.stdout.toString()}` );
From Node.js v13.9.0 Documentation
The same goes for Node.js v12.16.1 Documentation and Node.js v10.19.0 Documentation