Created
October 6, 2020 19:45
-
-
Save sarink/51850d83fde7de903473e31bacc7a933 to your computer and use it in GitHub Desktop.
promise-based node exec with stdout logging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { spawn } = require('child_process'); | |
const exec = (command, args = []) => { | |
return new Promise((resolve, reject) => { | |
console.log(''); | |
console.log(`${command} ${args.join(' ')}`); | |
const proc = spawn(command, args); | |
proc.stdout.pipe(process.stdout); | |
proc.stderr.pipe(process.stderr); | |
const stdout = []; | |
proc.stdout.on('data', (data) => { | |
stdout.push(data.toString().trim()); | |
}); | |
const stderr = []; | |
proc.stderr.on('data', (data) => { | |
stderr.push(data.toString().trim()); | |
}); | |
proc.on('close', (code) => { | |
const result = { command, args, stdout, stderr, code }; | |
return code === 0 ? resolve(result) : reject(result); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment