Node JS, delayed response

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 ?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

// simulate delay response
app.use((req, res, next) => {
    setTimeout(() => next(), 2000);
});

Solution 3

browser behavior is different from curl. browser will not render the page, until you call res.end(). so if you want to load a part of a web page after a delay, you need to load that second part separately via a websocket or an ajax request. I recommend using websocets. take a look at socket.io, it’s a simple way of using websockets in node.js.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply