首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用require fs.readFile读取json文件内容

使用require fs.readFile读取json文件内容
EN

Stack Overflow用户
提问于 2016-02-14 14:29:43
回答 3查看 71.4K关注 0票数 42

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

请注意,我不希望在运行时对文件进行任何更改。

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-02-14 16:00:40

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

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

如果有数千个请求在使用该文件,只需在请求处理程序外部请求它一次,就可以了:

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
});
票数 54
EN

Stack Overflow用户

发布于 2018-05-07 17:52:30

{
  "country": [    
    "INDIA",
    "USA"
  ],
  "codes": [   
    "IN",
    "US"
  ]
}

// countryInfo.json

const { country, code } = require('./countryInfo.json');

console.log(country[0]); // "INDIA"
console.log(code[0]); // "IN"
票数 1
EN

Stack Overflow用户

发布于 2018-10-28 19:50:33

我只想指出,即使变量应该删除,require似乎也会将文件保留在内存中。我的案例如下:

for (const file of fs.readdirSync('dir/contains/jsons')) {
  // this variable should be deleted after each loop
  // but actually not, perhaps because of "require"
  // it leads to "heap out of memory" error
  const json = require('dir/contains/jsons/' + file);
}

for (const file of fs.readdirSync('dir/contains/jsons')) {
  // this one with "readFileSync" works well
  const json = JSON.parse(fs.readFileSync('dir/contains/jsons/' + file));
}

由于“堆内存不足”错误,require的第一个循环不能读取所有的JSON文件。使用readFile的第二个循环可以工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35389060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档