Search code examples
node.jsdiscorddiscord.jsfs

Discord.JS Command Handler: How to read files from all directories within a directory?


I am running into some issue with checking the commands directory for my files. I want readdirSync to read all .js files from some directories inside the /commands/ directory (music, info etc.) but I don't seem to know or be able to find a way to do that.

Code below:

import { readdirSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export async function importer(client) {
    const commandFiles = readdirSync(join(__dirname, "../../", "/commands/")).filter((file) => file.endsWith(".js"));

    for (const file of commandFiles) {
        const command = await import(join(__dirname, "../../", "/commands/", `${file}`));
        client.commands.set(command.default.name, command.default);
    }
}

In the commandFiles, I can't seem to be able to find something to put after the / in commands so it can read the directories and their files within /commands/.

Any help is appreciated!

Thanks!


Solution

  • You need to read the subdirectories after you read the commands directory and use the subdirectory name as an argument for join:

    export async function importer(client) {
      const dir = join(__dirname, "../../commands/")
    
      const commandCategories = readdirSync(dir)
      for (let cat of commandCategories) {
        const commands = readdirSync(join(dir, cat)).filter(files => files.endsWith(".js"));
    
        for (const file of commands) {
          const command = import(join(dir, cat, file));
    
          // Add any logic you want before you load the command here
        
          client.commands.set(command.default.name, command.default);
        }
      }
    }