我想让这个函数在var中返回exec命令的结果。我该怎么做呢?
// System Serial Number
function systemSerialNumber(response) {
console.log("Request handler 'systemSerialNumber' was called.");
exec("dmidecode -t 1 | grep 'Serial Number:' | cut -d: -f2 | sed -e 's/^[ \t]*//g'", function (error, stdout, stderr) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stdout);
response.end();
});
}
答案 0 :(得分:1)
From http://nodejs.org/docs/v0.3.1/api/all.html#child_process.exec描述了如何异步获取命令的输出。但听起来你想同步得到结果,所以你可以回复它们,在这种情况下,你可能对这个问题更感兴趣:node.js execute system command synchronously
答案 1 :(得分:0)
我建议使用诸如步骤https://github.com/creationix/step
之类的库function systemSerialNumber(response) {
var output = "";
Step(
function runCommand() {
exec("dmidecode -t 1 | grep 'Serial Number:' | cut -d: -f2 | sed -e 's/^[ \t]*//g'", this);
},
function(error, stdout, stderr) {
output = stdout;
response.writeHead(200, {"Content-Type": "text/plain"}); response.write(stdout); response.end();
});
return output;
}