Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda