Koto
Koto

Reputation: 450

Simplest way to search subfolders of main command folder?

So this is my command handler code:

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;
        }
    }
}

What would be the simplest way to recursively search all the subfolders of .commands/, in such a way that I can use the commands within .commands/fun. I would prefer if the answer doesn't include the usage of a package to limit dependencies.

Upvotes: 0

Views: 122

Answers (1)

Cody Bennett
Cody Bennett

Reputation: 786

This will depend on the level of depth that you want.

You can scan any directories mapped above a single time and later flatten your results, or create a recursive function (the former makes less sense as you'll have to map again).

Note: One thing I will point out is that it's dangerous to hard code file paths. These are not OS-agnostic — see path.sep.

const fs = require('fs');
const path = require('path');

async function getFiles(directory) {
  const files = await Promise.all(
    fs.readdirSync(directory, { withFileTypes: true }).map(file => {
      const res = path.resolve(directory, file.name);

      return file.isDirectory() ? getFiles(res) : res;
    })
  );

  return Array.prototype.concat(...files);
}

Full implementation:

const fs = require('fs');
const path = require('path');

async function getFiles(directory) {
  const files = await Promise.all(
    fs.readdirSync(directory, { withFileTypes: true }).map(file => {
      const res = path.resolve(directory, file.name);

      return file.isDirectory() ? getFiles(res) : res;
    })
  );

  return Array.prototype.concat(...files);
}

module.exports = async (client, Discord) => {
  const command_files = await getFiles(path.resolve(__dirname, '..', 'commands'));

  for (const file of command_files) {
    const command = require(file);

    if (command.name) {
      client.commands.set(command.name, command);
    } else {
      continue;
    }
  }
};

Upvotes: 1

Related Questions