简体   繁体   English

如何发送和接收大型JSON数据

[英]How to send and receive large JSON data

I'm relatively new to full-stack development, and currently trying to figure out an effective way to send and fetch large data between my front-end (React) and back-end (Express) while minimizing memory usage. 我是全栈开发的新手,目前正在设法找到一种有效的方式在前端(React)和后端(Express)之间sendfetch大数据,同时最大程度地减少内存使用。 Specifically, I'm building a mapping app which requires me to play around with large JSON files (10-100mb). 具体来说,我正在构建一个映射应用程序,该应用程序需要我处理大型JSON文件(10-100mb)。

My current setup works for smaller JSON files: 我当前的设置适用于较小的JSON文件:

Backend: 后端:

const data = require('../data/data.json');

router.get('/', function(req, res, next) {
  res.json(data);
});

Frontend: 前端:

componentDidMount() {
      fetch('/')
      .then(res => res.json())
      .then(data => this.setState({data: data}));
  }

However, if data is bigger than ~40mb, the backend would crash if I test on local due to running out of memory. 但是,如果data大于〜40mb,则由于内存不足,如果在本地进行测试,后端将崩溃。 Also, holding onto the data with require() takes quite a bit of memory as well. 同样,使用require()保留数据也会占用大量内存。

I've done some research and have a general understanding of JSON parsing, stringifying, streaming, and I think the answer lies somewhere with using chunked json stream to send the data bit by bit, but am pretty much at a loss on its implementation, especially using a single fetch() to do so (is this even possible?). 我已经进行了一些研究,并对JSON解析,字符串化,流式传输有一个大致的了解,我认为答案就在于使用分块的JSON流来一点一点发送数据,但是在实现上却有很多损失,特别是使用单个fetch()这样做(甚至可以吗?)。

Definitely appreciate any suggestions on how to approach this. 绝对感谢有关如何解决此问题的任何建议。

First off, 40mb is huge and can be inconsiderate to your users especially if there' sa high probability of mobile use. 首先,40mb是巨大的空间,对于您的用户而言,这可能是不合理的,尤其是在移动使用可能性很高的情况下。

If possible, it would be best to collect this data on the backend, probably put it onto disk, and then provide only the necessary data to the frontend as it's needed. 如果可能的话,最好是在后端收集此数据,可能将其放到磁盘上,然后根据需要仅将必要的数据提供给前端。 As the map needs more data, you would make further calls to the backend. 当地图需要更多数据时,您将进一步调用后端。

If this isn't possible, you could load this data with the client-side bundle. 如果无法做到这一点,则可以通过客户端捆绑程序加载此数据。 If the data doesn't update too frequently, you can even cache it on the frontend. 如果数据更新不是太频繁,您甚至可以将其缓存在前端。 This would at least prevent the user from needing to fetch it repeatedly. 这至少将防止用户需要重复获取它。

Alternatively, you can read the JSON via a stream on the server and stream the data to the client and use something like JSONStream to parse the data on the client. 另外,您可以通过服务器上的流读取JSON并将数据流传输到客户端,并使用JSONStream之类的内容来解析客户端上的数据。

Here's an example of how to stream JSON from your server via sockets: how to stream JSON from your server via sockets 这是如何通过套接字从服务器流JSON的示例: 如何通过套接字从服务器流JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM