spawncommand
Advanced tools
Comparing version 1.0.1 to 1.1.0
{ | ||
"name": "spawncommand", | ||
"version": "1.0.1", | ||
"version": "1.1.0", | ||
"description": "spawn which returns a process with a promise property, fulfilled with { code, stdout, stderr }", | ||
@@ -30,4 +30,7 @@ "main": "src/index", | ||
"devDependencies": { | ||
"zoroaster": "^0.2.0" | ||
"zoroaster": "^0.3.0" | ||
}, | ||
"dependencies": { | ||
"catchment": "^1.0.0" | ||
} | ||
} |
@@ -0,51 +1,39 @@ | ||
const Catchment = require('catchment') | ||
const spawn = require('child_process').spawn | ||
const Writable = require('stream').Writable | ||
function getDataFromSet(set) { | ||
const arr = Array.from(set) | ||
return arr.join('').trim() | ||
} | ||
function addToSet(set, data) { | ||
return set.add(data) | ||
} | ||
function addToSetAsString(set, data) { | ||
return addToSet(set, String(data)) | ||
} | ||
function createWritableForSet(set) { | ||
const addData = addToSetAsString.bind(null, set) | ||
return createWritable(addData) | ||
} | ||
function createWritable(fn) { | ||
const ws = new Writable() | ||
ws._write = (chunk, enc, next) => { | ||
if (typeof fn === 'function') fn.call(null, chunk) | ||
next(null) | ||
} | ||
return ws | ||
} | ||
// better child_process.spawn for nodejs! | ||
function spawnCommand(command, args, options) { | ||
const proc = spawn(command, args, options) | ||
const stdErrCatchment = new Catchment() | ||
const stdOutCatchment = new Catchment() | ||
if (proc.stdout) { | ||
proc.stdout.pipe(stdOutCatchment) | ||
} else { | ||
stdOutCatchment.end() | ||
} | ||
if (proc.stderr) { | ||
proc.stderr.pipe(stdErrCatchment) | ||
} else { | ||
stdErrCatchment.end() | ||
} | ||
const promise = new Promise((resolve, reject) => { | ||
try { | ||
const stdoutData = new Set() | ||
const stderrData = new Set() | ||
const writeStdout = createWritableForSet(stdoutData) | ||
const writeStderr = createWritableForSet(stderrData) | ||
proc.on('error', reject) | ||
proc.on('exit', (code) => { | ||
resolve({ | ||
code, | ||
stdout: getDataFromSet(stdoutData), | ||
stderr: getDataFromSet(stderrData), | ||
}) | ||
}) | ||
if (proc.stdout) proc.stdout.pipe(writeStdout) | ||
if (proc.stderr) proc.stderr.pipe(writeStderr) | ||
} catch (err) { | ||
return reject(err) | ||
} | ||
proc.on('error', reject) | ||
proc.on('exit', (code) => { | ||
resolve(code) | ||
}) | ||
}) | ||
.then(code => Promise.all([ | ||
code, | ||
stdOutCatchment.promise, | ||
stdErrCatchment.promise, | ||
])) | ||
.then(res => ( | ||
{ | ||
code: res[0], | ||
stdout: res[1], | ||
stderr: res[2], | ||
} | ||
)) | ||
proc.promise = promise | ||
@@ -52,0 +40,0 @@ proc.spawnCommand = proc.spawnargs.join(' ') |
5
4303
1
41
+ Addedcatchment@^1.0.0
+ Addedcatchment@1.0.0(transitive)