Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS, delayed response

Tags:

node.js

var http = require('http');
var s = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.write('Hello\n');
      setInterval(function() {
          res.end(' World\n');
      },2000);
      console.log("Hello");
});
s.listen(8080);

After starting the above server, i run,

curl http://127.0.0.1:8080 

I get the required delay. output:

Hello <2 seconds> World

But in the browser the whole content loads after 2 seconds.

Hell World <together after 2s>

What am i doing wrong ?

like image 591
Jayaram Avatar asked Nov 12 '13 12:11

Jayaram


2 Answers

// simulate delay response
app.use((req, res, next) => {
    setTimeout(() => next(), 2000);
});
like image 153
Uday Hiwarale Avatar answered Sep 30 '22 14:09

Uday Hiwarale


The following piece of code opens up a response stream with the client and streams it to the client. So, in curl you'll get "Hello" first and "World" after 2 seconds (since you've set an interval of 2000 milliseconds).

      res.write('Hello\n');
      setInterval(function() {
          res.end(' World\n');
      },2000);

But the browser renders it only after the complete response stream is recieved. That is why you're getting the response after 2 seconds.

It is completely the browser's behavior. It doesn't utilize the response stream until the whole response is received. Once the stream is closed, the whole response will be ready to be utilized. However, in PHP there's a way to flush the response stream if need be.

However, if you're looking for streaming data on a frequent basis, this wouldn't be the best way to do it. I'd rather suggest you to use Comet technique or websockets.

I hope this is what you are looking for.

like image 37
Amith Koujalgi Avatar answered Sep 30 '22 13:09

Amith Koujalgi