So I have this code:
http://pastebin.com/42aHz5fy (sorry,I failed at using <pre> tags in StackOverflow editor)
The console.log() inside getStats function returns an object,but in the second console.log()(outside the function,after calling it),it returns "undefined".
And this is my console:
http://i.stack.imgur.com/aU465.png
Why is it returning undefined?
var getStats = function (){
fs.readFile('Documents/GitHub/kag-gather-irc-bot/stats.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
everyStats = JSON.parse(data);
console.log(everyStats);
return everyStats;
});
}
STATS = getStats();
console.log(STATS);
You can't return a value from an asynchronous method like that... all actions done on a value returned by an async call must be done within the callback.
So the solution is to use a callback which will be called once the async operation is completed and the desired value will be passed to the callback as an argument
var getStats = function (callback) {
fs.readFile('Documents/GitHub/kag-gather-irc-bot/stats.json', 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
everyStats = JSON.parse(data);
console.log(everyStats);
callback(everyStats);
});
}
getStats(function (STATS) {
console.log(STATS);
});
Because the getStats function isnt returning anything, only the function which is an argument of fs.readFile returns.
Here I have made a callback argument, so that you can do what you need with everyStats inside of a callback function.
var getStats = function (callback){
fs.readFile('Documents/GitHub/kag-gather-irc-bot/stats.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
everyStats = JSON.parse(data);
console.log(everyStats);
callback(everyStats);
});
}
getStats(function(stats) {
// do what you want with stats
});