2013-02-10 93 views
1

我想運行一些預定義的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); 

回答

0

這是因爲你放置res.end()。由於exec是異步的,res.end()實際發生在res.write之前,因此標籤爲(2)。在.end之後不會再發出任何寫入,所以瀏覽器不會獲得任何進一步的數據。

你應該在res.write後調用res.end()裏面的 exec回調函數。執行回調將在子進程終止時發出,並將獲得完整的輸出。

+0

啊公牛* cks。謝謝,我掙扎了一個小時。完全忘記了我選擇node.js的原因:異步行爲:) – stUrb 2013-02-10 15:09:42