2010-10-14 49 views
4
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') 

如何獲取數據流傳輸到瀏覽器?Nodejs - 流輸出到瀏覽器

回答

11

如果你只是一般問怎麼回事錯的,主要有兩個方面:

  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'); 

請注意,這實際上並不需要'流',因爲通常使用這個詞。如果你有一個長時間運行的進程,這樣你不想在內存中緩存stdout,直到它完成(或者如果你正在向瀏覽器發送一個文件等),那麼你會想'流'輸出。您可以使用child_process.spawn來啓動進程,立即編寫HTTP頭,然後每當在stdout上觸發'data'事件時,您都會立即將數據寫入HTTP流。在「退出」事件上,您將調用流結束來終止它。