Skip to content

Instantly share code, notes, and snippets.

@SCP002
Last active April 21, 2021 06:50
Show Gist options
  • Save SCP002/6e91fcd71899afef4a0e7dfb529ab73d to your computer and use it in GitHub Desktop.
Save SCP002/6e91fcd71899afef4a0e7dfb529ab73d to your computer and use it in GitHub Desktop.
Node.js: Spawn process. Keep StdOut and StdErr in the original order. Display output real time. Capture output on exit.
// Based on answer from https://stackoverflow.com/questions/57046930/node-js-spawn-keep-stdout-and-stderr-in-the-original-order
const { spawn } = require('child_process');
const options = {
shell: true, // Keep shell: true to redirect StdErr to StdOut.
stdio: [
'inherit', // StdIn. Fixes "ERROR: Input redirection is not supported, exiting the process immediately" on Windows.
'pipe', // StdOut.
'pipe', // StdErr.
],
};
const child = spawn('my-executable-name', ['arg1', '2>&1'], options); // Keep 2>&1 to redirect StdErr to StdOut.
let mergedOut = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => {
process.stdout.write(chunk, (_err) => { });
mergedOut += chunk;
});
child.on('close', (_code, _signal) => {
console.log('-'.repeat(30));
console.log(mergedOut);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment