sarah sarah - 6 months ago 14
Node.js Question

Javascript reaching variable from outside of anonymous function

I am trying to read asynchronously from a file by using node.js. Here is the code that I use:

var fs = require('fs');

fs.readFile('C:\\Users\\aonal\\Desktop\\gelenhamveri.txt', 'utf8', function(err, contents) {
console.log(contents);
//return contents // didn't work. I tried to return it to a variable.

});
console.log('after calling readFile');
console.log(contents); //empty. I want to use it here.


I can't reach the contents outside of function. I tried to return it or assign it to a global variable but it didn't work. My final purpose is to export all the code as a function then use it in different module like this:

module.exports = {
readFile : function(){//Same as above...}
}


So I need to return the contents. My question is how to return a variable from it to use outside of anonymous function?

Answer

Commonly, asynchronous functions like fs.readFile will take a callback function as last argument. That function will be called when the file has been read.

If you want to wrap such functions with your own code, you need to continue the same paradigm; in other words, your function should also accept a callback function:

var fs = require('fs');

module.exports = {
  readFile : function(callback) {
    fs.readFile('C:\\Users\\aonal\\Desktop\\gelenhamveri.txt', 'utf8', callback)
  }
}

And any calling code also needs to pass a callback function:

yourModule.readFile(function(err, contents) {
  if (err) {
    console.error('an error occurred!', err);
    return;
  }
  console.log(contents);
});

As suggested by others, instead of passing callback functions you can also use promises, which are an alternative method of asynchronous code handling.