0

我正在尝试通过child_process模块执行命令并将结果响应到客户端浏览器,如下所示,console.log(stdout)工作查找,但response.write()不起作用。

function start(response) {
    dir_list(function(stdout) {
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write(stdout);
        console.log(stdout);
        response.end();
});     

function dir_list(callback) {
     var exec = require('child_process').exec
     child = exec('ls -la', function(error, stdout, stderr) {
         callback(stdout);
     });
}

上面的代码由我重构,我将其称为 Node.js: Object value as stdout of child_process.exec,但不幸的是它对我不起作用。

顺便说一句,我原来的代码是:

  function start(response) {
      console.log("Request handler 'start' was called.");
      var exec = require('child_process').exec;
      exec("ls -lah", function (error, stdout, stderr) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write(stdout);
      console.log(stdout);
      response.end();
 });
4

1 回答 1

1

您的代码在函数}末尾缺少关闭。start

function start(response) {
    dir_list(function(stdout) {
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write(stdout);
        console.log(stdout);
        response.end();
    });
}

function dir_list(callback) {
     var exec = require('child_process').exec
     child = exec('ls -la', function(error, stdout, stderr) {
         callback(stdout);
     });
}
于 2012-04-28T18:16:16.633 回答