I have the following function in my nodejs, using express.
function metaInfo (id){
var dir = 'files/'+id;
var count = 0
fs.readFile(__dirname +'/' + dir+'/myfile.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
var myArr = obj.nodes;
var count = Object.keys(myArr).length;
console.log("counting :", count)
});
return count
};
when I call this function, the count is zero, however, it is the right value inside the fs.readFile . how can I return the updated value of count?
fs.readFile is an asynchronous function, so when your function returns count, the file has not been open yet.
Here's what you can do :
function metaInfo (id, callback){
var dir = 'files/'+id;
var count = 0
fs.readFile(__dirname +'/' + dir+'/myfile.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
var myArr = obj.nodes;
count = Object.keys(myArr).length;
callback(count);
});
};
metaInfo("yourId", function(count) {
// Here is your count
});
OR
use fs.readFileSync
Hope it helps,
Best regards,
fs.readFile is an async call.
you can use a function as a callback and invoke it ad the end of your async call or you can wrap your call in a promise
var Promise = require('bluebird');
var MyReadFileAsync = function (filename) {
return new Promise(function (resolve, reject) {
fs.readFile(filename, 'utf8', function (err,
data) {
if (err) reject(err);
obj = JSON.parse(data);
var myArr = obj.nodes;
resolve(Object.keys(myArr).length);
});
});
};
MyReadFileAsync(__dirname +'/' + dir+'/myfile.json').then(function(counter){
var myCounterUpdated = counter;
})
It is an asynchrone problem with your code.
You sould use the "async" library for NodeJS. Async documentation
For exemple, you can wrap your :
fs.readFile(__dirname +'/' + dir+'/myfile.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
var myArr = obj.nodes;
var count = Object.keys(myArr).length;
console.log("counting :", count)
});
To :
async.waterfall([
function(callback) {
fs.readFile(__dirname +'/' + dir+'/myfile.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
var myArr = obj.nodes;
var count = Object.keys(myArr).length;
console.log("counting :", count);
callback(null, count);
});
}
], function (err, result) {
// result now equals = count
return result;
});