Last active
July 9, 2017 09:15
-
-
Save eschwartz/d1173917c3b8bac75a6e0cd4b1d5faca to your computer and use it in GitHub Desktop.
exec-promise: Promise wrapper around child_process.exec
This file contains 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 childProcess = require('child_process'); | |
// otherwise we get a stupid warning. | |
process.stdout.setMaxListeners(100); | |
process.stderr.setMaxListeners(100); | |
/** | |
* Promisified child_process.exec | |
* | |
* @param cmd | |
* @param opts See child_process.exec node docs | |
* @param {stream.Writable} opts.stdout If defined, child process stdout will be piped to it. | |
* @param {stream.Writable} opts.stderr If defined, child process stderr will be piped to it. | |
* @param {bool} opts.killOnExit Kill the child process when the parent process exits | |
* | |
* @returns {Promise<{ stdout: string, stderr: stderr }>} | |
*/ | |
function execp(cmd, opts) { | |
opts || (opts = {}); | |
return new Promise((resolve, reject) => { | |
const child = childProcess.exec(cmd, opts, | |
(err, stdout, stderr) => err ? reject(err) : resolve(stdout.toString('utf8'))); | |
if (opts.stdout) { | |
child.stdout.pipe(opts.stdout); | |
} | |
if (opts.stderr) { | |
child.stderr.pipe(opts.stderr); | |
} | |
// Kill child on exit | |
const killChild = () => { | |
child.kill(); | |
}; | |
process.setMaxListeners(20); | |
process.on('exit', killChild); | |
child.on('exit', () => process.removeListener('exit', killChild)); | |
}); | |
} |
This file contains 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
import * as childProcess from 'child_process'; | |
import * as stream from 'stream'; | |
// otherwise we get a stupid warning. | |
process.stdout.setMaxListeners(100); | |
process.stderr.setMaxListeners(100); | |
interface IOptions { | |
stdout?: stream.Writable, | |
stderr?: stream.Writable, | |
killOnExit?: boolean | |
} | |
function execp(cmd:string, opts:IOptions = {}):Promise<string> { | |
return new Promise((resolve, reject) => { | |
const child = childProcess.exec(cmd, opts, | |
(err, stdout, stderr) => { | |
err ? reject(err) : resolve(stdout) | |
}); | |
if (opts.stdout) { | |
child.stdout.pipe(opts.stdout); | |
} | |
if (opts.stderr) { | |
child.stderr.pipe(opts.stderr); | |
} | |
// Kill child on exit | |
const killChild = () => child.kill(); | |
process.setMaxListeners(20); | |
process.on('exit', killChild); | |
child.on('exit', () => process.removeListener('exit', killChild)); | |
}); | |
} | |
export default execp; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment