node.js - 访问系统命令的退出代码和stderr [英] node.js - Accessing the exit code and stderr of a system command
问题描述
下面显示的代码段非常适合获取对系统命令的标准输出的访问权限。有没有办法可以修改这段代码,以便访问系统命令的退出代码和系统命令发送给stderr的任何输出?
The code snippet shown below works great for obtaining access to the stdout of a system command. Is there some way that I can modify this code so as to also get access to the exit code of the system command and any output that the system command sent to stderr?
#!/usr/bin/node
var child_process = require('child_process');
function systemSync(cmd) {
return child_process.execSync(cmd).toString();
};
console.log(systemSync('pwd'));
推荐答案
您不需要执行异步操作。你可以保留你的execSync函数。
You do not need to do it Async. You can keep your execSync function.
尝试包装它,传递给catch(e)块的Error将包含你正在寻找的所有信息。
Wrap it in a try, and the Error passed to the catch(e) block will contain all the information you're looking for.
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'));
如果没有抛出错误,则:
If an error is NOT thrown, then:
- 状态保证为0
- stdout是函数返回的内容
- stderr几乎肯定是空的因为它成功了
在极少数情况下,命令行可执行文件返回stderr但退出状态为0(成功),并且您想要读取它,您将需要异步功能。
In the rare event the command line executable returns a stderr and yet exits with status 0 (success), and you want to read it, you will need the async function.
这篇关于node.js - 访问系统命令的退出代码和stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!