Last active
May 17, 2021 20:35
-
-
Save BananaAcid/327bb84abf34571bb6a5348c29c4ac37 to your computer and use it in GitHub Desktop.
get process output / async JS
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
/* | |
* Get output and exitcode from a command | |
* | |
* @author Nabil Redmann <repo+gist@bananaacid.de> | |
* @license ISC | |
* | |
* import getOutput from './getOutput.mjs'; | |
* let {out, code} = getOutput('ls', ['-l', '*.txt']); | |
*/ | |
import { spawn } from 'child_process'; | |
let getOutput = async function (cmdstr, paramsArr = []) { | |
let out = []; | |
let ex = _ => new Promise((resolve, reject) => { | |
let p = spawn(cmdstr, paramsArr); | |
p.stdout.on('data', function (data) { | |
// console.log('stdout: ' + data.toString()); | |
let line = data.toString(); | |
out.push(line); | |
}); | |
// contains processing info | |
p.stderr.on('data', function (data) { | |
// console.log('stderr: ' + data.toString()); | |
let line = data.toString(); | |
out.push(line); | |
}); | |
p.on('exit', function (code) { | |
resolve(code.toString()); | |
}); | |
p.on('error', e => { | |
out.push(e.toString()); | |
resolve('ERROR'); | |
}) | |
}); | |
let code = await ex(); | |
return {out, code}; | |
//return out; | |
} | |
export default getOutput; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment