下面显示的代码段非常适合获取对系统命令的标准输出的访问权限。有没有办法可以修改这段代码,以便也可以访问系统命令的退出代码和系统命令发送给stderr的任何输出?
#!/usr/bin/node
var child_process = require('child_process');
function systemSync(cmd) {
return child_process.execSync(cmd).toString();
};
console.log(systemSync('pwd'));
答案 0 :(得分:37)
您不需要执行Async。你可以保留你的execSync功能。
尝试包裹它,传递给catch(e)块的错误将包含您正在寻找的所有信息。
var child_process = require('child_process');
function systemSync(cmd) {
try {
return child_process.execSync(cmd).toString();
}
catch (error) {
error.status; // Might be 127 in your example.
error.message; // Holds the message you typically want.
error.stderr; // Holds the stderr output. Use `.toString()`.
error.stdout; // Holds the stdout output. Use `.toString()`.
}
};
console.log(systemSync('pwd'));
如果没有抛出错误,那么:
在极少数情况下,命令行可执行文件返回一个stderr但是以状态0(成功)退出,并且您想要读取它,您将需要异步函数。
答案 1 :(得分:8)
您需要exec的异步/回调版本。返回了3个值。最后两个是stdout和stderr。此外,child_process
是一个事件发射器。听取exit
事件。回调的第一个元素是退出代码。 (从语法上可以看出,您希望使用节点4.1.1来使下面的代码按照书面形式工作)
const child_process = require("child_process")
function systemSync(cmd){
child_process.exec(cmd, (err, stdout, stderr) => {
console.log('stdout is:' + stdout)
console.log('stderr is:' + stderr)
console.log('error is:' + err)
}).on('exit', code => console.log('final exit code is', code))
}
尝试以下方法:
`systemSync('pwd')`
`systemSync('notacommand')`
你会得到:
final exit code is 0
stdout is:/
stderr is:
其次是:
final exit code is 127
stdout is:
stderr is:/bin/sh: 1: notacommand: not found
答案 2 :(得分:5)
您还可以使用child_process.spawnSync()
,因为它会返回更多内容:
return:
pid <Number> Pid of the child process
output <Array> Array of results from stdio output
stdout <Buffer> | <String> The contents of output[1]
stderr <Buffer> | <String> The contents of output[2]
status <Number> The exit code of the child process
signal <String> The signal used to kill the child process
error <Error> The error object if the child process failed or timed out
因此,您要查找的退出代码为ret.status.