I currently have a Discord.JS command handler that loads all commands in the command folder. However it is getting a bit messy now due to all the commands, therefore I have been trying to implement Sub-Folders. This would clean up the files inside the commands folder, organizing them into folder groups.
I currently have this code for loading the commands in the same folder.
But I am stuck on how I could go into each folder in the commands directory and load the commands. If someone could help me, that would be appreciated.
const allCommands = fs.readdirSync('./commands');
for (const command of allCommands) {
try {
const loadedCommand = require(`./commands/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${command})`);
} catch (error) {
logger.error(`Failed to load command ${command}. **Please report the following error:**`);
logger.error(error);
}
}
Move everything into its own function with the path as a parameter. Every time you find a folder, call the function with the folder path.
(function readdir(path='./commands') {
const allCommands = fs.readdirSync(path);
for (const command of allCommands) {
if(fs.statSync(`${path}/${command}`).isDirectory()) {
readdir(`${path}/${command}`);
continue;
}
try {
const loadedCommand = require(`${path}/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${path}/${command})`);
} catch (error) {
logger.error(`Failed to load command ${path}/${command}. **Please report the following error:**`);
logger.error(error);
}
}
})();
Honestly, I don't recommend importing this way. You might have better luck if you import each of your commands into a seperate javascript file then export each of your commands from there, it should make your controller level code much easier to read