假设对于来自 API 的每个响应,我需要将响应中的值映射到我的 Web 应用程序中的现有 json 文件并显示来自 json 的值。在这种情况下,读取 json 文件的更好方法是什么?要求或 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
});
关于javascript - 使用 require vs fs.readFile 读取 json 文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389060/