From 5b0d221daa5b796585190ba435d5a6d213cbba33 Mon Sep 17 00:00:00 2001 From: mmcw-dev Date: Thu, 15 Mar 2018 14:50:36 -0400 Subject: [PATCH] Add the async/await exec wrapper that I use, for an experimental feature. --- app/lib/exec/index.js | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 app/lib/exec/index.js diff --git a/app/lib/exec/index.js b/app/lib/exec/index.js new file mode 100644 index 0000000..b6c0a5c --- /dev/null +++ b/app/lib/exec/index.js @@ -0,0 +1,46 @@ +'use strict' + +const execRaw = require('child_process').exec + +/** + * Promisified child_process.exec + * + * @param cmd + * @param arg + * @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. + * + * @returns {Promise<{ stdout: string, stderr: stderr }>} + */ +async function exec(...args) { + let cmd = args[0] + let argz = null + let opts = null + if (typeof args[1] === 'object' && Array.isArray(args[1])) { + argz = args[1] + } + if (argz === null && typeof args[1] === 'object') { + opts = args[1] + } else if (typeof args[2] === 'object') { + opts = args[2] + } + if (opts === null) { + opts = { maxBuffer : 1024 * 1024 } + } + return new Promise((resolve, reject) => { + const child = execRaw(cmd, opts, + (err, stdout, stderr) => err ? reject(err) : resolve({ + stdout: stdout, + stderr: stderr + })); + if (opts.stdout) { + child.stdout.pipe(opts.stdout); + } + if (opts.stderr) { + child.stderr.pipe(opts.stderr); + } + }); +} + +module.exports = exec \ No newline at end of file