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 ?
// simulate delay response
app.use((req, res, next) => {
setTimeout(() => next(), 2000);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With