I'm pretty new to Node.js and I had a confusing interaction with fs.readFile()
.
Initially, I thought that I could read a file using
fs.readFile("file.txt",function(err,data) {
if(err) {throw err;}
console.log(data);
});
However, this printed null. I consulted the documentation and it gives the exact same example and claims that it works fine!
Then I consulted stack overflow and found in this post and this post that a solution is to wrap fs.readFile()
in your own function that takes a callback:
function read(file,callback) {
fs.readFile("file.txt",function(err,data) {
if(err) {throw err;}
callback(data);
});
}
read(file, function(data) {
console.log(data);
});
Alternatively, it's possible to just assign data to a new variable:
var content;
fs.readFile("file.txt",function(err,data) {
if(err) {throw err;}
content = data;
console.log(content);
});
My understanding is that when an asynchronous function completes and returns some value (here the contents of the file) then the callback runs on the returned data.
If
fs.readFile(file,callback)
expects to be passed a callback function, then why does it seemingly run the callback beforefs.readFile()
has completed?Why does assigning the data to another variable change the way it behaves?
Thanks.