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

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

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

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

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