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

2024-04-24

假设对于来自 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
});

我想你会 JSON.parse 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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 require 与 fs.readFile 读取 json 文件内容 的相关文章