I know that when developing in node, you should always try to avoid blocking (sync) functions and go with async functions, however I a little test to see how they compare.
I need to open a json file that contains i18n data (like date and time formats, etc) and pass that data to a class that uses this data to format numbers etc in my views.
It would be kind of awkward to start wrapping all the class's methods inside callbacks, so if possible, I would use the synchronous version instead.
console.time('one');
console.time('two');
fs.readFile( this.dir + "/" + locale + ".json", function (err, data) {
if (err) cb( err );
console.timeEnd('one');
});
var data = fs.readFileSync( this.dir + "/" + locale + ".json" );
console.timeEnd('two');
This results in the following lines in my console:
two: 1ms
one: 159ms
It seems that fs.readFileSync is about 150 times faster than fs.readFile and takes about 1ms to load a 50KB json file (minified). All my json files are around 50-100KB.
I was thinking also maybe somehow memoizing or saving this json data to session so that the file is read only once per session (or when the user changes their locale). I'm not entirely sure how to do that, it's just an idea.
Is it okay to use fs.readFileSync
in my case or will I get in trouble later?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…