0

I am a beginner in node.js I have some problems with setTimeout(function(){.....},time); thingo. This works fine when i curl the local server but not as expected in google chrome (i haven't tested other browsers)

My Code is:

/* simple node.js createserver */

var http = require('http');

http.createServer(function (request, response) {
     response.writeHead(200);
  response.write('Somthing\r\n');

  setTimeout(function(){
        response.end('\n This came out after 5 seconds :) ');
  }, 5000);
   response.write('Hello World\n');
}).listen(8124);



console.log('Server running at http://127.0.0.1:8124/');

When i curl 127.0.0.1:8124 everything works as expected. But when i point that in browser, it remains idle for some time (which i guess is that 5 seconds) and shows all the contents at once? Is this the expected behavior of node.js or i am missing something? Can the browser do thing like the curl does (i.e, printing two lines first, and waiting for 5 seconds and printing another line)?

cipher
  • 2,414
  • 4
  • 30
  • 54
  • 1
    possible duplicate of [Node Js problems with response.write](http://stackoverflow.com/questions/6068820/node-js-problems-with-response-write) – Dogbert Jun 30 '13 at 16:54
  • 1
    [Possible solution](http://stackoverflow.com/a/16999405/149260) is to add `Transfer-Encoding: chunked` – mak Jun 30 '13 at 17:42
  • that didn't solve it :( – cipher Jun 30 '13 at 17:46

2 Answers2

1

It is expected-- the browser isn't meant to display the page until it has finished loading (I believe that there may be an exception for large chunks, but for the most part this will be true)

bobbybee
  • 1,758
  • 1
  • 16
  • 27
1

Try this

http.createServer(function (request, response)

  response.setHeader('Content-Type', 'text/html; charset=UTF-8');
  response.writeHead(200);
  response.write('Somthing\r\n');

  setTimeout(function(){
    response.end('\n This came out after 5 seconds :) ');
  }, 5000);

  response.write('Hello World\n');
  //No point writing Hello World here as it is written immediately

}).listen(8124);
user568109
  • 47,225
  • 17
  • 99
  • 123
  • Thanks. and that last Hello World was just from my previous code :) (there's no point writing this) – cipher Jun 30 '13 at 18:14
  • Adding the `text/html; charset=UTF-8` as the Content-Type made it work. It tells browsers what the page is encoded in. Browsers may not get the Content-Type unless they go through the whole content. Browsers can progressively load the page. It is just that doing so requires it to know some page metadata beforehand. – user568109 Jul 01 '13 at 04:40