Skip to content

Instantly share code, notes, and snippets.

@DanielFGray
Last active March 4, 2018 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielFGray/e624bba42aa0276cb8229ed9185afbfb to your computer and use it in GitHub Desktop.
Save DanielFGray/e624bba42aa0276cb8229ed9185afbfb to your computer and use it in GitHub Desktop.
spawn child processes with a promise
const { spawn } = require('child_process')
const readToEnd = stream =>
new Promise(((resolve, reject) => {
const parts = []
stream.on('error', reject)
stream.on('data', part => parts.push(part))
stream.on('end', () => resolve(Buffer.concat(parts)))
}))
const cmd = (args, data) => {
const instance = spawn(args[0], args.slice(1), { stdio: ['pipe', 'pipe', 'inherit'] })
instance.stdin.end(data)
const read = readToEnd(instance.stdout)
const exit = new Promise(((resolve, reject) => {
instance.on('error', reject)
instance.on('exit', exitCode => {
if (exitCode === 0) {
resolve()
} else {
reject(new Error('process exited with non-zero code'))
}
})
}))
return exit
.then(() => read)
.then(b => b.toString('utf8'))
}
module.exports = cmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment