0

I'm trying to include multiple folders in JavaScript, specific: Discord JS, here's my code:

const commandFiles = fs.readdirSync('./aPublic').filter(file => file.endsWith('.js')); // I wanted to include it here

for (const file of commandFiles) {
    const command = require(`./aPublic/${file}`); // I wanted to include it here too!
    client.commands.set(command.name, command);
}

I've tried to use ./aPublic && ./bAdmin and also ('./aPublic') && ('./bAdmin') but it only read the "bAdmin" folder rather than both of them, I wanted to include like 7 folders in both code.

2
  • Have you tried path.join(__dirname, './aPublic/') for readdirSync path? const path = require("path"); Commented Jul 6, 2020 at 10:18
  • path.join(__dirname, './aPublic/' && './bAadmin) like that? what about the const command? i'm new to JS so yea Commented Jul 6, 2020 at 10:27

1 Answer 1

1

Let's put your list of directories in an array like below, use .map() to read each of them, join the path of each file with its corresponding directory and flatten the result using .flat().

const arrDir = ['./aPublic', './bPublic'];

const commandFiles = arrDir
    .map(dir => {
        const listFiles = fs.readdirSync(dir);
        return listFiles.map(file => path.join(__dirname, dir, file));
    })
    .flat()
    .filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(file);
    client.commands.set(command.name, command);
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Zhxck I have some errors in the for loop above. Give me a few seconds to correct them.
Edit : Ok i will
I've just updated the code. Basically we need to join the path first before filtering them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.