Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - i can't reproduce progressive response from server

well,

i'm completely new to node.js. Starting to try it, i'm following the introduction made by Ryan Dahl (http://www.youtube.com/watch?v=jo_B4LTHi3I) and at this point (around 0:17:00) there's an explanation about how server handles responses,

The basic example is to have a 'hello' output from webserver and then after 2 secs it comes the 'world', this code is supposed to do that

//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 the Hello World but there's only one response from server with the complete result, that is, request > 2 sec > 'Hello World'. Instead of request > Hello > 2 secs > World.

Why is that?, How can i change this behaviour?

I'm using v0.8.18, curl -i http://localhost:3000 returns the right 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

like image 673
Alexander Fradiani Avatar asked Jan 26 '13 18:01

Alexander Fradiani


People also ask

Why node JS Cannot be used for CPU intensive applications?

Nodejs is good for IO intensive tasks but bad for CPU intensive tasks. The reason Nodejs is bad for CPU intensive task is that it runs on the event loop, which runs on a single thread. The event loop is responsible for everything that runs on the user-land of Nodejs. This event loop runs on a single thread.

Is Nodejs real time data intensive?

Node. js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.”


2 Answers

It is the browser that buffers the incoming data until some amount has been received, before starting to render. Your Node code does just as you expect, it will sent the first part of the response, then wait for 2 seconds, then send the second half.

If you want to observe this behavior, you can send a bunch of spaces to make the browser empty its buffer. If you add this after your initial write, you will see the browser render the first half of the request.

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

Obviously don't do this in real code, but it's good to demonstrate the behavior.

like image 161
loganfsmyth Avatar answered Oct 19 '22 16:10

loganfsmyth


With curl, your code performs as expected. A browser waits for the whole body, but curl prints "hello", waits 2 seconds then prints "worls". I copied your exact code and it's ok.

like image 44
randunel Avatar answered Oct 19 '22 15:10

randunel