Home > database >  Items not being added to array/map in Node
Items not being added to array/map in Node

Time:12-11

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.

CodePudding user response:

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

CodePudding user response:

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();

CodePudding user response:

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()
  • Related