Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
How could I automatically read all of the directories and add all files that end in .js to discord collection

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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/');
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!