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