Search code examples
node.jsdiscord.jsfsenoent

Why can't my DJS bot find my commands folder?


I'm making a command handler for my discord.js bot. But the bot cannot find the "commands" folder.

Line code I have problems with:

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

Folders

Error message :

Uncaught Error: ENOENT: no such file or directory, scandir './commands'

What is the problem and what is the solution?


Solution

  • Try wrapping the ./commands with grave accents:

    `./commands`
    

    instead of './commands' or append a "/" to the end, helps sometimes.

    If you want the handler to recursively search for all your commandfiles, e.g. you created subdirectories to organize your commands, you can use the function I use (and recommend):

    const fs = require('fs');
    const path = require('path');
    const rootDir = path.dirname(require.main.filename);
    const fileArray = [];
    
    const readCommands = (dir) => {
    
        const __dirname = rootDir;
    
        // Read out all command files
        const files = fs.readdirSync(path.join(__dirname, dir));
    
        // Loop through all the files in ./commands
        for (const file of files) {
            // Get the status of 'file' (is it a file or directory?)
            const stat = fs.lstatSync(path.join(__dirname, dir, file));
    
            // If the 'file' is a directory, call the 'readCommands' function
            // again with the path of the subdirectory
            if (stat.isDirectory()) {
                readCommands(path.join(dir, file));
            }
            else {
                const fileDir = dir.replace('\\', '/');
                fileArray.push(fileDir + '/' + file);
            }
        }
    };
    
    
    readCommands('commands');