假设对于来自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
});
发布于 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
});
发布于 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"
发布于 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
的第二个循环可以工作。
https://stackoverflow.com/questions/35389060
复制相似问题