Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  98] [ 3]  / answers: 1 / hits: 76744  / 8 Years ago, sun, february 14, 2016, 12:00:00

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

More From » node.js

 Answers
5

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

[#63323] Thursday, February 11, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;