So I am a beginner in learning Node and trying to understand the asynchronous part of it. The following code in readIn
should wait for readFile
to finish and then execute whenDone
to update the arr
variable, but whatever value I pass in as it always shows that the arr is empty. I don't think the arr
was ever mutated or the function whenDone
never waited for the readFile
to finish.
Can someone please explain what I'm doing wrong or misunderstood?
Thank you
var fs = require('fs');
var arr = [];
function readIn(callback){
fs.readFile(process.argv[2],'utf8',function whenDone(err, fileContent){
arr = fileContent.split('\n');
callback();
})
}
var result = arr.length -1
function printOut(){
console.log(result);
}
readIn(printOut);