I have the following simple NodeJS code:
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);
If I run the script with node scriptname.js
and then access it via curl in terminal like this:
curl http://localhost:8080
I get an output as expected, first it prints This will be printed before.
, then after 3 seconds it prints This printed 3 secs later, ait?
.
However, when I open http://localhost:8080
in my browser (newest versions of Chrome, Firefox) page loads for 3 seconds and it prints the text This will be printed before.
This printed 3 secs later, ait?
all at once. Why does this happen and how could I make the same behavior in the browser?
edit: So, as Ken stated in his answer
...this is simply due to the behavior of the browser rendering engine to render the contents. The rendering engine cashes the contents until response.end();
and advised to go and check out Socket.IO, I came up with this working example which uses express and 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>