promisify-child-process
seriously like the best async child process library
Based upon child-process-async
,
but more thorough, because that package doesn't seem very actively maintained.
promisify-child-process
provides a drop-in replacement for the
original child_process
functions, not just duplicate methods that
return a Promise
. So when you call exec(...)
we still return a
ChildProcess
instance, just with .then()
and .catch()
added to
make it promise-friendly.
Install and Set-up
npm install --save promisify-child-process
If you are using a old version of Node without build-in Promise
s or
Object.create
, you will need to use polyfills.
Usage
const { exec, spawn, fork, execFile } = require('child_process');
const { exec, spawn, fork, execFile } = require('promisify-child-process');
If for any reason you need to wrap a ChildProcess
you didn't create,
you can use the exported promisifyChildProcess
function:
const {promisifyChildProcess} = require('promisify-child-process');
async function() {
const { stdout, stderr } = await promisifyChildProcess(
some3rdPartyFunctionThatReturnsChildProcess()
)
}
Examples
exec()
async function() {
const { stdout, stderr } = await exec('ls -al');
const child = exec('ls -al', {});
child.stdin.write(...);
child.stdout.pipe(...);
child.stderr.on('data', (data) => ...);
const { stdout, stderr } = await child;
}
spawn()
async function() {
const { stdout, stderr, exitCode } = await spawn('ls', [ '-al' ]);
const child = spawn('ls', [ '-al' ], {});
child.stdin.write(...);
child.stdout.pipe(...);
child.stderr.on('data', (data) => ...);
const { stdout, stderr, exitCode } = await child;
}