用require vs fs.readFile读取json文件内容 [英] Read json file content with require vs fs.readFile

查看:232
本文介绍了用require vs fs.readFile读取json文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose that for every response from an API, i need to map the value from the response to an existing json file in my web application and display the value from the json. What are the better approach in this case to read the json file? require or fs.readfile. Note that there might be thousands of request comes in at a same time.

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

Note that I do not expect there is any changes to the file during runtime.

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文件为了比较,在这种情况下,要求更好,因为它会马上解析文件,并且同步:

I suppose you'll JSON.parse the json file for the comparison, in that case, require is better because it'll parse the file right away and it's sync:

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

如果您有数千个请求使用该文件,则需要它一直在你的请求处理程序之外,就是这样的:

If you have thousands of request using that file, require it once outside your request handler and that's it:

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

这篇关于用require vs fs.readFile读取json文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆