Read json file content with require vs fs.readFile

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

Leave a Comment