简体   繁体   中英

How do you make folders inside a command folder and make it work in discord.js v12

So I am currently wanting to make it so I can make folders inside my commands folder like moderation etc. Just so I can clean it up more. However I really do not know how to do this as everytime I do it does not work.

const Discord = require(`discord.js`);
const client = new Discord.Client();

const commandFiles = readdirSync(join(__dirname, "commands")).filter(file => file.endsWith(".js"));
client.commands = new Discord.Collection();

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

So this is my current code so far so if I make another folder and add an command there it will not work and won't boot up.

Thanks in advance

You can use nested for loops to read every subdirectory and files in those subdirectories. Let's say you have a ./commands folder, and in that folder are more folders grouping your commands — moderation, fun, public, etc, and those folders contain your command files.

const cmdDirs = fs.readdirSync('./commands');

/* Loop through subdirectories in commands directory */
for (let dir of cmdDirs) {
    /* Read every subdirectory and filter for JS files */
    let commandFiles = fs.readdirSync(`./commands/${dir}`)
    .filter(f => f.endsWith('.js'));

    /* Loop through every file */
    for (let file of commandFiles) {
        /* Set command file */
        let command = require(`./commands/${dir}/${file}`);
        client.commands.set(command.name, command);
    };
};

I have created a function to recursively read files in a directory and all of its subdirectories.

const Discord = require("discord.js");
const client = new Discord.Client();

function readFiles(dir) {
    const paths = readdirSync(dir, { withFileTypes: true });

    return paths.reduce((files, path) => {
        if (path.isDirectory()) {
            files.push(...readFiles(join(dir, path.name)));
        } else if (path.isFile()) {
            files.push(join(dir, path.name));
        }

        return files;
    }, []);
}

const commandFiles = readFiles("commands").filter(file => file.endsWith(".js"));
client.commands = new Discord.Collection();

for (const file of commandFiles) {
    const command = require(join(__dirname, file));
    client.commands.set(command.name, command);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM