运行shell命令并在http服务器中显示

时间:2013-02-10 00:34:07

标签: node.js

我想运行一些预定义的shell命令,并将它们作为纯文本返回到http服务器中。 在(1)中写入的内容正在提供给我的浏览器,但最终必须是stdout的(2)中的内容未被提供。任何人都可以帮我解决这个问题吗?

var http = require('http'),
url = require('url'),
exec = require('child_process').exec,
child,
poort = 8088;


http.createServer(function(req, res) {
 res.writeHead(200, {'Content-Type': 'text/plain'});

    var pathname = url.parse(req.url).pathname;
    if (pathname == '/who'){
        res.write('Who:'); // 1
        child = exec('who',
                     function(error, stdout, stderr){
                        res.write('sdfsdfs');   //2
                     })


    } else {
        res.write('operation not allowed');
    }

 res.end();

}).listen(poort);

1 个答案:

答案 0 :(得分:0)

这是因为你放置res.end()的位置。

由于exec是异步的,res.end()实际上发生在你标记为(2)的res.write之前。在.end之后不能再发出写入,因此浏览器不会获得任何进一步的数据。

在res.write之后,你应该在exec回调中调用res.end()。当子进程终止时将发出exec回调,并将获得完整的输出。