Last active
March 4, 2018 22:25
-
-
Save DanielFGray/e624bba42aa0276cb8229ed9185afbfb to your computer and use it in GitHub Desktop.
spawn child processes with a promise
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 { 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