微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用require vs fs.readFile读取json文件内容

我想您将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
});

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。