使用 require vs fs.readFile 读取 json 文件内容 [英] Read json file content with require vs fs.readFile

查看:40
本文介绍了使用 require vs fs.readFile 读取 json 文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设对于来自 API 的每个响应,我需要将来自响应的值映射到我的 Web 应用程序中现有的 json 文件并显示来自 json 的值.在这种情况下读取 json 文件的更好方法是什么?要求或 fs.readfile.请注意,可能有数千个请求同时传入.

Suppose that for every response from an API, i need to map the value from the response to an existing json file in my web application and display the value from the json. What are the better approach in this case to read the json file? require or fs.readfile. Note that there might be thousands of request comes in at a same time.

请注意,我不希望在运行期间对文件有任何更改.

Note that I do not expect there is any changes to the file during runtime.

request(options, function(error, response, body) {
   // compare response identifier value with json file in node
   // if identifier value exist in the json file
   // return the corresponding value in json file instead
});

推荐答案

我想你会 JSON.parse json 文件进行比较,在这种情况下,require 更好,因为它会立即解析文件并同步:

I suppose you'll JSON.parse the json file for the comparison, in that case, require is better because it'll parse the file right away and it's sync:

var obj = require('./myjson'); // no need to add the .json extension

如果您有数以千计的请求使用该文件,那么在请求处理程序之外需要它一次,就是这样:

If you have thousands of request using that file, require it once outside your request handler and that's it:

var myObj = require('./myjson');
request(options, function(error, response, body) {
   // myObj is accessible here and is a nice JavaScript object
   var value = myObj.someValue;

   // compare response identifier value with json file in node
   // if identifier value exist in the json file
   // return the corresponding value in json file instead
});

这篇关于使用 require vs fs.readFile 读取 json 文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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