Basics
Asynchronous and synchronous operations
const fs = require('fs');
const cache = {};
const inconsistentRead = function(fileName, callback) {
if (cache[fileName]) {
// invoked synchronously
// callback(cache[fileName]);
// make it asynchronous - and puts it before any IO event in the event loop
process.nextTick(() => callback(cache[fileName]));
// or make it asynchronous - and puts it at after all the IO events in the event loop
setImmediate(() => callback(cache[fileName]));
} else {
// invoked asynchronously
fs.readFile(fileName, 'utf8', (err, data) => {
cache[fileName] = data;
callback(data);
})
}
};Last updated