I am trying to create a moderation bot and I face a error that shows I don't have commands and setWelcome file in my project even when I do. Here is the complete error -
node:internal/fs/utils:344
throw err;
^
Error: ENOTDIR: not a directory, scandir './commands/setWelcome.js'
at Object.readdirSync (node:fs:1390:3)
at Object.<anonymous> (/home/runner/Him/index.js:12:26)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
errno: -20,
syscall: 'scandir',
code: 'ENOTDIR',
path: './commands/setWelcome.js'
}
Here is my code in index.js -
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.commands = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.commands.set(command.name, command);
}
}
client.once('ready', (c) => {
console.log(`Logged in as ${c.user.tag}`);
});
client.on('messageCreate', message => {
//My command handler code here
});
client.login(process.env.TOKEN);
and, My setWelcome.js file is completely empty
Here is my project directory -
index.js//file
commands//folder and then inside commands
setWelcome.js //file
and yes, I do have package.json and package-lock.json files. I would be really grateful to anyone who helps, Thank you! by the way.. I am using repl.it for this project
It seems like you are trying to loop through your folder in two conflicting ways (you are using two nested for loops). This would make sense if the commands folder contained subfolders that contained the files you want to target. However, since your command files are directly inside your commands folder, one loop will suffice.
The readdirSync function expects a path to a directory and returns a list of its content as described in the fs documentation, but ./commands/${folder} is already a path to a file inside the commands folder. The following should help:
\\create a list of files in command directory that end with .js
const commandFiles = fs.readdirSync(`./commands/`).filter(file => file.endsWith('.js'));
\\loop over items in the list
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
Note: Maybe the trailing backslash in ./commands/ should be omitted. Please comment if so.