Why can’t it find the directory?



Hey tried to create a command handler in discord.js but ran into some trouble along the way, from my limited knowledge in javascript and discord.js the code should at least be able to find the directory…

enter image description here

Here’s the code that’s trying to find the directory “cmds”:

const cmdFiles = fs.readdirSync('../cmds/').filter(file => file.endsWith('.js'));
for(const file of cmdFiles) {
    console.log("hej");
    console.log(file);
    const cmd = require(`../cmds/${file}`);

    client.cmds.set(cmd.name, cmd);
}

For someone thinking that i’ve might have set it up in some kind of faulty way, here’s the rest of the code from main.js:

require('dotenv').config();   

const Discord = require('discord.js');      

const client = new Discord.Client();
const prefix = '-';

const fs = require('fs');


client.cmds = new Discord.Collection();

const cmdFiles = fs.readdirSync('../cmds/').filter(file => file.endsWith('.js'));
for(const file of cmdFiles) {
    console.log("hej");
    console.log(file);
    const cmd = require(`../cmds/${file}`);

    client.cmds.set(cmd.name, cmd);
}



client.on("ready", () => {
    console.log(`${client.user.tag} : Online`); 
});


client.on("message", msg => {
    if(!msg.content.startsWith(prefix) || msg.author.bot) return;

    const args = msg.content.slice(prefix.length).split(/ +/);
    const cmd = args.shift().toLowerCase();

    if(cmd === 'ping') {
        client.cmds.get('ping').execute(msg, args);
    }
});



client.login(process.env.STATSRUST_TOKEN);           

While I do not think that it’s set up in any wrong way I might as well be wrong haha. Again thanks for the help!

Answer

The path passed to fs.readdirSync() is interpreted as relative to the current working directory, not to the JS file, so you probably should replace ../cmds/ by ./cmds/ or simply cmds/.

You can change the working directory by running the cd command before running Node.js.



Source: stackoverflow