This is the code I currently have, how would adapt this to check each sub-directory:
const fs = require('fs')
module.exports = (client, Discord) =>{
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'))
for(const file of command_files){
const command = require(`../commands/${file}`);
if(command.name) {
client.commands.set(command.name, command);
} else {
continue
}
}
}
And this is the layout I have for the commands folder the folder layout
CodePudding user response:
You need to wrap the whole code into a function and use some recursion.
Please note that, when using recusion, a depth
variable is a wise way to handle it
Something like this should do it:
const fs = require('fs')
module.exports = (client, Discord) =>{
const depth = 3;
const finder = (path, currentDepth = 0) => {
if (currentDepth >= depth) {
return; // Breaks here
}
const dirContent = fs.readdirSync(path);
const command_files = dirContent.filter(file => file.endsWith('.js'));
const folders = dirContent.filter(file => {
const dirPath = path file;
// Exists is a directory verification
return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
);
for(const file of command_files){
const filePath = '../' path file;
const command = require(filePath);
if(command.name) {
client.commands.set(command.name, command);
} else {
continue
}
}
// Loops through folders
folders.map((folder) => finder(path folder '/', currentDepth 1));
}
finder('./commands/');
}