2

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?

sarah
  • 580
  • 1
  • 6
  • 24

3 Answers3

2

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.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • 1
    Well, I tried it and it worked like a charm. I am kinda new to Javascript and node.js and your explanation along with your answer is so precious, thank you. – sarah May 22 '16 at 17:12
1

You can try using Promise

var fs = require("fs");
var Promise = require("promise"); 
var read = Promise.denodeify(fs.readFile);
var p = read("C:\\Users\\aonal\\Desktop\\gelenhamveri.txt", "utf8")
.then(function (contents) {
  console.log(contents)
})
guest271314
  • 1
  • 15
  • 104
  • 177
0

bluetoft and Maantje answers are correct. You have to use readFileSync() and assign the output to a variable

Thib
  • 187
  • 6