0

I am trying to read async from a file angularJs. Having a horrible time trying to make the variable mySuperFile available outside of the callback. Please see code below.

fs.readFile('myfile','utf8', function (err, data){
    var mySuperFile = JSON.parse(data);
});

//I want mySuperFile available HERE
T M
  • 516
  • 5
  • 18
  • 1
    the thing you want to do is impossible. You should go on working with your file **inside** of your callback function. If you want to make it more beautiful have a look at Promise solutions – smnbbrv Dec 03 '15 at 09:03
  • http://stackoverflow.com/questions/10058814/get-data-from-fs-readfile – vivid Dec 03 '15 at 09:07

2 Answers2

3

Because readFile is asynchronous, everything that uses this must also be asynchronous.

Here is an approach:

var fetchMySuperFile = new Promise(function(resolve, reject) {
   fs.readFile('myfile','utf8', function (err, data){
       resolve(JSON.parse(data));
   });
};

fetchMySuperFile.then(function(mySuperFile) {
   // OK, you have it now.
});

This can still be useful. The nature of javascript promises is you can invoke fetchMySuperFile.then multiple times, but it will still have only called readFile one time.

Of course, since it's angular, you might want to use $q instead of Promise. The reason why is that, after a $q has resolved, angular refreshes. (You won't need to invoke $scope.$apply())

Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
  • Thanks @Andrew Shepherd. I think your response is probably the closest I got to a solution. This problem here is that I am trying to edit a bower file using the gulp-json-editor. For it to work, jEditor needs mySuperFile to be in its scope and not nestled in another function (I dont know why that it the case). Thanks anyway – T M Dec 03 '15 at 10:43
0

Due to async nature of js, you can't do something like this:

var mySuperFile;
fs.readFile('myfile','utf8', function (err, data){
    mySuperFile = JSON.parse(data);
});
console.log(mySuperFile);

This is because the line console.log( mySuperFile ); won't wait until the function above finished.

Ajith Pai
  • 34
  • 5