0

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!

nikoszz
  • 163
  • 1
  • 3
  • 13

1 Answers1

0

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);
    }
  }
}
DarkenLM
  • 26
  • 2
  • 5
  • Thanks! This works, but I have run into another issue: `Cannot read properties of undefined (reading 'name')`. It's for the ```client.commands.set(command.default.name, command.default)```. The command files start with ```export default```. – nikoszz Apr 27 '22 at 17:43
  • @nikoszz From the error you sent me, it looks like there is an empty file or a file without a default export somewhere. If not, try to log the `command` and see if the file is being correcly imported. – DarkenLM Apr 27 '22 at 22:06
  • I already fixed it, sorry for not telling here about it. But thanks anyway! – nikoszz Apr 28 '22 at 07:10