Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
nodejs express function not returning the variable from fs.readFile

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

Here is a good example

Hope it helps,

Best regards,

over 4 years ago · Santiago Trujillo Report

0

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;
})
over 4 years ago · Santiago Trujillo Report

0

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;
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!