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

标签 javascript node.js express

假设对于来自 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/

相关文章:

javascript - Safari 扩展消息传递

javascript - Kendo UI DateTimePicker - 显示从 00 :30 till 24:00 开始的 30 分钟间隔

node.js - 如何在 Cassandra 中使用 cqlsh 插入带有 map<text, boolean> 字段的自定义类型?

javascript - 在 nodejs 困惑中返回 next()

node.js - 如何使用 Express/Socket.io 在 Node.js 上使用 HTTPS

javascript - 从数字A到B计数动画

javascript - Nodejs 和 Angular 应用程序使用 JWT 发送 401 Unauthorized 和 200 OK

svn - 提交时 Node.js 中的符号链接(symbolic link)

mysql - mvc 与 Node/express 和 mysql

javascript - 如何避免 $http promise Angular 1.5 的竞争条件