Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda