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

193
Views
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 answers
Answer question

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 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!