var http = require("http");
var sys = require('sys')
var filename = process.ARGV[2];
var exec = require('child_process').exec;
var com = exec('uptime');
http.createServer(function(req,res){
res.writeHead(200,{"Content-Type": "text/plain"});
com.on("output", function (data) {
res.write(data, encoding='utf8');
});
}).listen(8000);
sys.puts('Node server running')
如何将数据传输到浏览器?
如果您只是一般性地询问出了什么问题,那么主要有两件事:
- 你正在使用
child_process.exec()
不正确地
- 你从未打过电话
res.end()
您正在寻找的东西更像是这样的:
var http = require("http");
var exec = require('child_process').exec;
http.createServer(function(req, res) {
exec('uptime', function(err, stdout, stderr) {
if (err) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.end(stderr);
}
else {
res.writeHead(200,{"Content-Type": "text/plain"});
res.end(stdout);
}
});
}).listen(8000);
console.log('Node server running');
请注意,这实际上并不需要通常使用的“流”一词。如果您有一个长时间运行的进程,因此您不想在内存中缓冲标准输出直到它完成(或者如果您正在向浏览器发送文件等),那么您可能希望“流式传输”输出。您将使用 child_process.spawn 启动进程,立即写入 HTTP 标头,然后每当 stdout 上触发“数据”事件时,您将立即将数据写入 HTTP 流。在“退出”事件中,您可以在流上调用 end 来终止它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)