1234567891011121314151617181920212223242526272829303132333435363738394041 |
- const child_process = require("child_process");
- const spawnExec = (cmds,opts={}) => {
- let cmd = cmds[0];
- let proc = child_process.spawn(cmd, cmds.slice(1), opts);
-
- console.log(cmds.join(' '))
- return new Promise(function (resolve, reject) {
- let stdout = [];
- let stderr = [];
- proc.stdout.on("data", function (buf) {
- stdout.push(buf);
- // 回调函数
- opts.stdout && opts.stdout(buf);
- });
- proc.stderr.on("data", function (buf) {
- stderr.push(buf);
- // 回调函数
- opts.stderr && opts.stderr(buf);
- });
- proc.on("exit", function (code) {
- let stdoutAll = Buffer.concat(stdout);
- let stderrAll = Buffer.concat(stderr);
-
- // 回调函数
- opts.exit && opts.exit(code);
- code ? reject({
- code,
- stdout: stdoutAll.toString(),
- stderr: stderrAll.toString()
- }) : resolve({
- stdout: stdoutAll.toString(),
- stderr: stderrAll.toString()
- });
- });
- });
- }
- module.exports = spawnExec
|