NodeJS代码在通过浏览器运行时以及在terminal中通过curl运行时执行方式不同

我有以下简单的NodeJS代码:

var http = require("http"); http.createServer( function(request, response){ response.writeHead(200); setTimeout(function(){ response.write("This printed 3 secs later, ait?"); response.end(); }, 3000); response.write("This will be printed before.\n"); }).listen(8080); 

如果我使用node scriptname.js运行脚本,然后在terminal中通过curl来访问它,如下所示:

 curl http://localhost:8080 

我得到一个预期的输出,首先它打印This will be printed before. ,然后在3秒后打印, This printed 3 secs later, ait?

但是,当我在我的浏览器(最新版本的Chrome,Firefox)中打开http://localhost:8080页面加载3秒钟并打印文本时, This will be printed before. This printed 3 secs later, ait? This will be printed before. This printed 3 secs later, ait? 一次全部。 为什么会发生这种情况,我怎么能在浏览器中做出相同的行为?

编辑:正如Ken在他的回答中所说的那样

这只是由于浏览器渲染引擎渲染内容的行为。 渲染引擎将caching内容,直到response.end();

并build议去看看Socket.IO,我想出了这个使用Express和Socket.IO的实例 :

//timeoutTest.js

 var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); server.listen(8080); app.use(express.static(__dirname + '/')); app.get('/', function (req, res) { res.sendfile(__dirname + '/timeoutTest.html'); }); io.sockets.on('connection', function (client) { client.emit('msg', "This prints right now on connection."); setTimeout(function(){ client.emit('msg', "This prints out after 3 secs."); }, 3000); }); 

//timeoutTest.html

 <!DOCTYPE html> <html> <head> <script src="/socket.io/socket.io.js"></script> <script src="jquery.js"></script> <script> $(document).ready(function(){ var server = io.connect('http://localhost'); server.on('msg', function(data){ $('body').append(data + "<br/>"); }); }); </script> </head> <body> </body> </html> 

我认为这只是由于浏览器渲染引擎呈现内容的行为。

渲染引擎将caching内容,直到response.end(); 到达,然后呈现整个。

基本上,浏览器中的HTML内容不会由增量server push (如response.write自动更新。

您必须通过Ajax和DHTML / js技术pull数据从服务器pull浏览器客户端。

卷起terminal在节点服务器的纯粹输出方面是完全不同的故事。

如果你在node服务器和浏览器客户端之间寻求更多的交互行为,如果你想要server pushfunction, websocket是要走的路,也是调查node stream东西。

Socket.IO是着名的,对于node stream https://github.com/substack/stream-handbook应该对你很有意思&#x3002;

我个人在我自己的项目上做到这一点:

http://kenokabe.github.io/MarkdownLive/

我使用Markdown写东西,需要一个stream预览,所以我自己创build。 预览屏幕是浏览器HTML页面,HTML内容以stream方式递增地呈现和更新。