如何将json对象流发送到客户端? [英] How to send stream of json object to the client?

查看:183
本文介绍了如何将json对象流发送到客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个重复的问题,但找不到任何解决方案.我已经尝试过在这个快速的时间内搜索它,但是我很不走运.

我的问题是如何向客户端发送json对象的 stream (如果流是正确的术语,则为idk).

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

示例我正在读取数据库上的数据,并且每发现5条记录,我就会将数据以json格式发送给客户端.然后使用Angular httpclient lib读取客户端上的数据.

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.

我已经尝试过expressjs response.write(),但是直到我调用response.end(),客户端才能够接收数据.

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?

我在考虑socket.io,但这太过分了.

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

修改

其他示例

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.
}

或者类似这样的东西.我原以为数据会每隔1秒到达一次,但10秒钟后它们会同时出现.

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);
}

推荐答案

所以我发现上面的示例代码没有问题,并且是正确的方法.

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

当我尝试直接向浏览器打开url API时,可以看到浏览器正在接收数据.

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

问题出在我用来获取数据的有角度的httpclient库上,如果所有内容都已下载,它将显示数据.

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.

但是幸运的是,我发现了这个包 oboe.js ,它可以做我想做的事情流json数据.因此,当快速js将通过res.write()发送数据时,oboe将能够检索数据并准备使用.

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.
});

这篇关于如何将json对象流发送到客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆