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

194
Visualizações
How to read a file (Synchronously?) in a while loop in javascript (Discord.js)?

This is possibly a duplicate question, but I can't seem to figure it out.

Essentially, I am making a code that runs in a while loop where I need to then read a file within that while loop, and it seems that the fileRead in the code just stops the while loop from getting to the end. I'm pretty newbie to javascript still, so it's probably an easy fix.

What I've tried so far is changing my jsonReader function to sync (readFileSync) and that just stopped the code before it did hardly anything. (that is now what the current code is as) I've also tried making a second function for specifically reading the files I need Synchronously and that didn't seem to work either. I'm not even sure if this has to do with synchronism

My Code:

module.exports = {
    name: 'xprun',
    description: "runs the xp handler",
    execute(message) {
 
        const name = message.author.username;
        const server = message.guild.id;
 
        const fs = require('fs');
 
        function jsonReader(filePath, cb) {
            fs.readFileSync(filePath, 'utf-8', (err, fileData) => {
                if (err) {
                    return cb && cb(err);
                }
                try {
                    const object = JSON.parse(fileData);
                    return cb && cb(null, object);
                } catch (err) {
                    return cb && cb(err);
                }
            });
        }
 
        console.log('Starting the loop...'); //
        
        var run = true;
        var i = 0;
 
        while (run == true) {
            i++
 
            console.log('Running the loop...'); // Loop stops and re-runs here
 
            // read #1
 
                jsonReader(`./userData/rank/${server}_server/1.json`, (err, data) => {
 
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(data.id); //
                    }
 
            // read #2
 
                jsonReader(`./userData/xp/${server}_server/${name}_xp.json`, (err, data) => {
 
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(data.rank); //
                    }
 
                    console.log('The loop was completed'); //
                    
                    if (i >= 5) {
                        run = false;
                    }
 
                }); // end read #1
 
            }); // end read #2
 
        } // end while
 
        console.log('The loop was ended'); //
 
    } // end execute
 
} // end
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As @CherryDT mentioned in the comments, readFileSync does not accept a callback. Because readFileSync is synchronous, it does not need a callback; readFile accepts a callback only because it is asynchronous, because it needs to wait until it has read the file before calling the code in the callback. The synchronous method does not need to wait in this way, so you can move the callback code out of the callback like so:

function jsonReader(filePath, cb) {
    try {
        const fileData = fs.readFileSync(filePath, 'utf-8');
        const object = JSON.parse(fileData);
        return cb && cb(null, object);
    } catch (err) {
        return cb && cb(err);
    }
}

The reason your loop was infinitely running was because you set run to false only within your callback cb method, but because readFileSync does not accept a callback, your callback was never being run. With the above code, your callback should now be running, and the loop should no longer run infinitely (unless there are other issues within your callbacks).

about 4 years ago · Juan Pablo Isaza 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