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
});
There are two versions for
fs.readFile
, and they areAsynchronous version
Synchronous version
To use
require
to parse json file as belowBut, note that
require
is synchronous and only reads the file once, following calls return the result from cacheIf your file does not have a
.json
extension, require will not treat the contents of the file asJSON
.Use node-fixtures if dealing with JSON fixtures in your tests.
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:If you have thousands of request using that file, require it once outside your request handler and that's it:
If your file is empty, require will break. It will throw an error:
With
readFileSync/readFile
you can deal with this:or:
I only want to point out that it seems
require
keeps the file in memory even when the variables should be deleted. I had following case:The first loop with
require
can't read all JSON files because of "heap out of memory" error. The second loop withreadFile
works.