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

184
Views
Items not being added to array/map in Node

I have this code which loops through all directories in the folder commands and then loops through each file in each of those directories. It then imports the module, converts it to JSON and adds it to an array called commands and a map called client.commands.

let commands = [];
client.commands = new Map();
fs.readdir(__dirname + "/../commands/", (err, dirs) => {
    if (err) return console.error(err);
    for (let dir of dirs) {
        fs.readdir(__dirname + `/../commands/${dir}/`, (err, files) => {
            if (err) return console.error(err);
            for (let file of files) {
                let command = require(`../commands/${dir}/${file}`);
                commands.push(command.data.toJSON());
                client.commands.set(command.data.name, command);
                console.log(commands);
            }
        });
    }
});
console.log(commands);

If I console.log the value of commands in the inner most for loop, the output is exactly as expected. However, if I log it on the outside of the entire code block, it just prints an empty list.

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

I think you should use recursion to read the files inside the folders recursively. And below link the question that already asked I think will help to solve this. Node.js fs.readdir recursive directory search

about 4 years ago · Santiago Gelvez Report

0

This looks like discord.js to me.

client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));

for (const file of commandFiles) {
    const command = require(`.commands/${file}`);
    client.commands.set(command.name, command);
}

Your commands should look like this

module.exports = {
    name: "name",
    description: "description",
    execute() {
    // execution code
    }
}

You can then use it by calling the function or getting the variables

client.commands.get(/* Name of command */).execute();
about 4 years ago · Santiago Gelvez Report

0

since readdir() is asynchrose, your outer console.log() is called before the function in the middle is fully executed.

I adjusted the syntax to the more modern async and await since fallback functions are not the best Practice anymore, unfortunately I couldn't test it, but it is atleast the correct way to go ;)

let commands = [];
client.commands = new Map();

async function main() {
    try {
        const dirs = await fs.readdir(__dirname + "/../commands/")
        for (let dir of dirs) {
            const files = await fs.readdir(__dirname + `/../commands/${dir}/`)
            for (let file of files) {
                let command = require(`../commands/${dir}/${file}`);
                commands.push(command.data.toJSON());
                client.commands.set(command.data.name, command);
                console.log(commands);
            }
        }
    } catch (error) {
        console.error(err)
    }

    console.log(commands);
}

main()
about 4 years ago · Santiago Gelvez 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!