检索node.js child_process的结果

问题描述

| 我无法绕过node.js的异步特性。让我们假设我想要一个执行\'ls \'命令并将结果(作为字符串)返回给浏览器的路由。使用child_process.exec将如何处理呢?以下是不正确的,但是按照我正在努力的方向进行:
function dir_list() {
  var sys = require(\'sys\');
  var exec = require(\'child_process\').exec
  child = exec(\'ls -la\',function(error,stdout,stderr) {
    //I would like to return stdout but can\'t figure out how
    return stdout;
  });
  return child;
}

app.get(\'/\',function(req,res){
  res.render(\'index\',{
  title: \'MyPage\',subtitle: \'Below is a directory listing\',results: dir_list()
});
这不是我的app.js的全部代码,但实际上我正在寻求有关dir_list()来将结果变量设置为\“ ls -la \”的输出的帮助。     

解决方法

        将回调传递到您的dir_list并使用ls -la结果调用它
function dir_list(cb) {
  var sys = require(\'sys\');
  var exec = require(\'child_process\').exec
  child = exec(\'ls -la\',function(error,stdout,stderr) {
    //I would like to return stdout but can\'t figure out how
    cb(stdout);
  });
}

app.get(\'/\',function(req,res){
  dir_list(function(dir_list_output) {
      res.render(\'index\',{
      title: \'MyPage\',subtitle: \'Below is a directory listing\',results: dir_list_output});
  });
});
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...