运行shell命令并显示在http服务器中
问题描述:
我想运行一些预定义的shell命令并将它们作为纯文本返回到http服务器中。 在(1)处写入的内容正在传送给我的浏览器,但最终必须是标准输出的(2)处的内容未被传送。任何人都可以帮我实现这个目标吗?运行shell命令并显示在http服务器中
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);
答
这是因为你放置res.end()。由于exec是异步的,res.end()实际发生在res.write之前,因此标签为(2)。在.end之后不会再发出任何写入,所以浏览器不会获得任何进一步的数据。
你应该在res.write后调用res.end()里面的 exec回调函数。执行回调将在子进程终止时发出,并将获得完整的输出。
啊公牛* cks。谢谢,我挣扎了一个小时。完全忘记了我选择node.js的原因:异步行为:) – stUrb 2013-02-10 15:09:42