【问题标题】:Retrieving results of node.js child_process检索 node.js child_process 的结果
【发布时间】:2011-06-18 05:23:04
【问题描述】:

我很难理解 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”的输出。

【问题讨论】:

    标签: node.js


    【解决方案1】:

    将回调传递给您的 dir_list 并使用 ls -la result 调用它

    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});
      });
    });
    

    【讨论】:

    • 感谢您的回复。这个例子正是我需要完成的。
    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2017-02-11
    • 2011-03-27
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多