I'm running Node.js from latest Ubuntu. I got the following code:
var http = require('http');
var s = http.createServer(function(req, res){
res.writeHead(200, {'content-type':'text/html'});
res.write('Hello ');
setTimeout(function(){
res.end('world');
}, 3000);
});
s.listen(8000);
Which I run by executing "node server.js", which is all fine. But the thing is that for some reason, no content is outputted until the setTimeout is called - that's 3 seconds after the request.
I more or less followed the example at http://www.youtube.com/watch?v=jo_B4LTHi3I (see 17:08), but I'm unable to get the same, "streamed" kind of result like he gets (his browser first outputs "Hello" and then "world" 3 seconds later).
I've tried different browsers and even tried to "curl" in Terminal, just like he does on the clip. But it's all the same.
Is some kind of output buffering turned on by default, or why does it act like this?
Thanks in advance!
That's because the browser renders the page only after it receives res.end() which is after 3 seconds. In the case of the implementation shown on the video notice that the line reads
res.write('Hello \n');
Using curl, the line break leads to 'hello' being output to the console and 'world' printed after a lag of 3 seconds.
In both cases i.e. with res.write('Hello') or res.write('Hello \n'), the browser renders it only after receiving res.end(). Moreover if the browser does not receive res.end(), the response will time-out and nothing will be displayed.