2013-06-30 84 views
0

我在node.js的初學者我有一些問題setTimeout(function(){.....},time); thingo。當我蜷縮在本地服務器但在谷歌瀏覽器不預期(我沒有測試過其他瀏覽器)的Node.js和setTimeout和谷歌瀏覽器

我的代碼也能正常工作:

/* simple node.js createserver */ 

var http = require('http'); 

http.createServer(function (request, response) { 
    response.writeHead(200); 
    response.write('Somthing\r\n'); 

    setTimeout(function(){ 
     response.end('\n This came out after 5 seconds :) '); 
    }, 5000); 
    response.write('Hello World\n'); 
}).listen(8124); 



console.log('Server running at http://127.0.0.1:8124/'); 

當我curl 127.0.0.1:8124一切正常。但是,當我指出,在瀏覽器中,它仍然閒置了一段時間(我的猜測是,5秒),並顯示所有內容一次?這是node.js的預期行爲,還是我錯過了一些東西?瀏覽器可以像捲曲事都(即,打印兩行第一,並等待5秒鐘,打印另一行)?

+1

的[節點的js問題回覆於]可能重複(http://stackoverflow.com/questions/6068820/node-js-problems-with-response-write) – Dogbert

+1

[可能的解決方法(http://stackoverflow.com/a/16999405/149260)是添加'傳輸編碼:chunked' – mak

+0

相信沒有解決它:( – cipher

回答

1

嘗試此

http.createServer(function (request, response) 

    response.setHeader('Content-Type', 'text/html; charset=UTF-8'); 
    response.writeHead(200); 
    response.write('Somthing\r\n'); 

    setTimeout(function(){ 
    response.end('\n This came out after 5 seconds :) '); 
    }, 5000); 

    response.write('Hello World\n'); 
    //No point writing Hello World here as it is written immediately 

}).listen(8124); 
+0

感謝和。最後的Hello World只是從我以前的代碼:)(有沒有點寫這篇) – cipher

+0

你可以說剛剛發生的事情爲它現在的工作? – cipher

+0

添加'text/html的; charset = UTF-8「作爲Content-Type使其工作。它告訴瀏覽器頁面編碼的內容。瀏覽器可能不會獲得Content-Type,除非他們瀏覽整個內容。瀏覽器可以逐步加載頁面。只是這樣做需要事先知道一些頁面元數據。 – user568109

1

據expected--瀏覽器並不意味着顯示頁面,直到它已完成加載(我認爲有可能是大段大段的例外,但在大多數情況下,這將是真實的)