2015-09-30 39 views
1

下面显示的代码旨在将当前工作目录输出到控制台。相反,它会输出“未定义”。为了获得这种学习体验,作为系统函数的返回值获得所需的结果非常重要。关于如何使这项工作的任何想法?如何获取系统命令的输出作为函数的返回值?

#!/usr/bin/node 
var child_process = require('child_process'); 
function system(cmd) { 
    child_process.exec(cmd, function (error, stdout, stderr) { 
    return stdout; 
})}; 
console.log(system('pwd')); 
+0

*“为了这种学习体验,重要的是我要获得所需的结果作为系统函数的返回值。”*这是不可能的。 'child_process.exec'是一个异步进程(这就是为什么你必须传递一个回调)。有关为什么你得到'undefined'(以及如何解决这个问题)的信息,请参阅http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call –

回答

4

exec是异步执行的。将回调传递给您的功能,然后设置好。

#!/usr/bin/node 
var child_process = require('child_process'); 

function system(cmd, callback) { 
    child_process.exec(cmd, function (error, stdout, stderr) { 
    //You should handle error or pass it to the callback 
    callback(stdout); 
    }); 
} 

system('pwd', function(output){ 
    console.log(output); 
}); 

这就是你将如何做到这一点,我相信是你在找什么。

function systemSync(cmd) { 
    return child_process.execSync(cmd).toString(); 
} 

console.log(systemSync("pwd")); 
+0

谢谢。很棒。其实我一直在寻找同步和异步的方式来做这件事,因为我的头部缠绕回调时遇到了一些麻烦。所以,你的答案是最有帮助的。谢谢。 – user3311045

相关问题