0

This can be a duplicate question but cant find any solution out there. I already tried to search it on this fast hours but I am out of luck.

My question is how I can send stream(idk if stream is the right term) of json objects to the client.

Example I am reading data on the DB, and on every 5 records it found I will send the data to the client in json format. Then read the data on the client using Angular httpclient lib.

I already tried expressjs response.write(), but the client was unable to receive the data until I call response.end().

What is the proper way of doing this?

I was thinking about socket.io but that would be overkill.

Edit

Other exmple

function getData(res: Response, req: Request):void {
  for(let i = 0; i<100; i++{
    res.write(JSON.stringify({data:1}) + '\n');
  }

  res.end(); // There is data received on the browser until this was called.
}

Or something like this. I was expecting a data will reach every 1 second but they came up at the same time after 10s.

function getData(res, req){
  const s = setInterval(()=>{
    res.write(JSON.stringify({value: 'test value'}));
  }, 1000);

  setTimeout(()=>{
    clearInterval(s);
    res.end();
  }, 10000);
}
zer09
  • 1,507
  • 2
  • 28
  • 48
  • This might help - https://stackoverflow.com/questions/18857693/does-express-js-support-sending-unbuffered-progressively-flushed-responses – Anand Undavia Dec 11 '18 at 08:37
  • @AnandUndavia the solution there, I think that still boils down to ```res.end()``` – zer09 Dec 11 '18 at 10:29

1 Answers1

0

So I found this out that the sample code above is doesn't have problem and also the right way to do it.

When I tried to open the url API directly to the browser, I can see that the browser is receiving the data.

The problem is on the angular httpclient lib that I use to fetch the data, it will show the data if everything is already downloaded.

But luckily I found this package oboe.js , it can do what I want to stream the json data. So when the express js will send data via res.write() oboe will able to retrieve the data and ready for consumption.

You can do it as simple as this.

oboe('your url').node('!', data=>{
  // process your data here.
  // the '!' selector means that oboe will just show the data if it is a valid json.
});
zer09
  • 1,507
  • 2
  • 28
  • 48