I have a sample code and outputs are as below: code:
for(var i = 0; i <20; i++) {
var fs = require("fs");
fs.readFile('input2.txt', function (err, data) {
if (err) return console.error(err);
console.log("first started\n");
console.log(data.toString());
});
console.log("first Ended");
console.log("second started");
var data = fs.readFileSync('input1.txt');
console.log(data.toString());
console.log("second Ended");
}
Output:
first Ended second started second Ended first Ended second started and so on till 20 times first started
1 first started 1 and so on till 20 times
As input2.txt has just one character in it and input1.txt has no of lines in it. I was assuming that callback function would be invoked after printing input from 1st file after one iteration as the file read operation should be completed by that time. But its not the case. Means it is completing sync operation first then only callback is getting work. How would that be possible? If callback has to wait for so long, what is the purpose of asynchronous call here?