Nodejs - 将输出流输出到浏览器

Har*_*rry 4 node.js

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')
Run Code Online (Sandbox Code Playgroud)

如何将数据流式传输到浏览器?

rus*_*l_h 12

如果你一般只是问什么是错的,那么主要有两个方面:

  1. 您的使用child_process.exec()不正确
  2. 你从未打过电话 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');
Run Code Online (Sandbox Code Playgroud)

请注意,在通常使用该词的意义上,这实际上不需要"流式传输".如果你有一个长时间运行的进程,这样你就不想在内存中缓冲stdout直到它完成(或者你正在向浏览器发送文件等),那么你会想要'流'输出.您可以使用child_process.spawn来启动进程,立即编写HTTP头,然后每当在stdout上触发'data'事件时,您就会立即将数据写入HTTP流.在"退出"事件上,您将在流上调用end来终止它.