Read json file content with require vs fs.readFile
There are two versions for fs.readFile
, and they are
Asynchronous version
require('fs').readFile('path/test.json', 'utf8', function (err, data) {
if (err)
// error handling
var obj = JSON.parse(data);
});
Synchronous version
var json = JSON.parse(require('fs').readFileSync('path/test.json', 'utf8'));
To use require
to parse json file as below
var json = require('path/test.json');
But, 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
.
Since no one ever cared to write a benchmark, and I had a feeling that require works faster, I made one myself.
I compared fs.readFile (promisified version) vs require (without cache) vs fs.readFileSync.
You can see benchmark here and results here.
For 1000 iterations, it looks like this:
require: 835.308ms
readFileSync: 666.151ms
readFileAsync: 1178.361ms
So what should you use? The answer is not so simple.
- Use require when you need to cache object forever. And better use Object.freeze to avoid mutating it in application.
- Use readFileSync in unit tests or on blocking application startup - it is fastest.
- Use readFile or promisified version when application is running and you don't wanna block event loop.
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
});