12
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 ?

1
  • 1
    hint:- "res.end()" makes a complete result that will be given to browser. so as soon as end method is called, response will be given to browser. I understand this is not answer but it might help.
    – Pranav
    Nov 12, 2013 at 12:21

3 Answers 3

18

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 a timer of 2000 milliseconds).

      res.write('Hello\n');
      setTimeout(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.

1
  • but is there any way this feature can be faked in the browser using node ?
    – Jayaram
    Nov 12, 2013 at 12:25
10
// simulate delay response
app.use((req, res, next) => {
    setTimeout(() => next(), 2000);
});
1
  • This use a "middleware", which catch all. It is easier to plug into any application in the mode "if (dev) app.use(...);"
    – jehon
    Oct 12, 2022 at 19:50
6

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.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.