2

Hi I'm trying to load files within different folders for example

-- Main directory
  -- bot folder
    - index.js
    - package.json
    - package-lock.json
    -- commands
        -- fun
            - kick.js
            - ban.js
        -- some other category

However in my code I'm only seem to be able to load the .js files in the Commands folder rather than the sub folders.

Here is the code I'm working with:

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

    const commands = commandFiles.map(file => require(`../Commands/${file}`));

    commands.forEach(cmd => {
        console.log(`Command ${cmd.name} loaded`);
        this.commands.set(cmd.name, cmd);
    });

Help appreciated.

Jasme
  • 87
  • 5
  • To read from subdir refer `https://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search` – navnath Sep 03 '21 at 01:56

1 Answers1

1

You can create multiple collections, one for each of your subfolders. Here is what I've done for my bot, and it's perfectly working :

client.commandsAdmin = new Discord.Collection();
client.commandsUser = new Discord.Collection();

const commandsAdminFiles = fs.readdirSync('./commands/admin').filter(file => file.endsWith('.js'));
const commandsUserFiles = fs.readdirSync('./commands/user').filter(file => file.endsWith('.js'));


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

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

When processing the command in your code, you would have to check if it belongs to one of the collections, then get which collection does contain the command, and then use client.commandsFun.get(command).execute(...) for example, if the command belong to the 'fun' subfolder.

Vincent Gonnet
  • 146
  • 1
  • 13