Node.js - I cannot play a progressive response from the server

a,

I am completely new to node.js. Starting to try, I follow the introduction made by Ryan Dahl ( http://www.youtube.com/watch?v=jo_B4LTHi3I ) and at that moment (around 0:17:00) there is an explanation of how the server processes the responses,

The main example is getting "hi" output from a web server, and then after 2 seconds it comes to the "world", this code should do it

//Require the webserver library var http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(200, { 'content-type' : 'text-plain' }); res.write('Hello\n'); //Asynchronous behavior setTimeout(function() { res.end('World\n'); }, 2000); }); server.listen(3000); 

So, I run it and I get Hello World, but there is only one response from the server with the full result, i.e. request> 2 sec> 'Hello World'. Instead of query> Hello> 2 secs> World.

Why is this ?, How can I change this behavior?

I am using v0.8.18, curl -i http://localhost:3000 returns the correct headers ... HTTP/1.1 200 OK content-type: text-plain Date: Sat, 26 Jan 2013 18:10:05 GMT Connection: keep-alive Transfer-Encoding: chunked

+6
source share
2 answers

This is a browser that buffers incoming data until any amount is received before starting rendering. Your Node code works exactly as you expect it to send the first part of the response, then wait 2 seconds, then send the second half.

If you want to observe this behavior, you can send a bunch of spaces so that the browser does not clear its buffer. If you add this after the first entry, you will see that the browser displays the first half of the request.

 var str = ''; for (var i = 0; i < 2000; i++){ str += ' '; } res.write(str); 

Obviously, do not do this in real code, but it is good to demonstrate behavior.

+6
source

With curl, your code works as expected. The browser waits for the whole body, but the curl prints "hello", waits 2 seconds, then prints "problems." I copied your exact code and everything is in order.

+1
source

All Articles