Reputation: 87
Hi I'm trying to rewrite some code in which the the bot loads .js files within a specific folder. Originally, to access the folder I would load my command files from I would have done the following and repeated the same code to access different folders:
fs.readdirSync("../src/Commands/Moderation")
.filter(file => file.endsWith(".js"))
.forEach(file => {
const command = require(`../Commands/Moderation/${file}`);
console.log(`Command ${command.name} loaded`);
this.commands.set(command.name, command);
});
However, I want a better method than the above. As you can seen in the code above I want to load a js file inside folder called Moderation, bear in mind I have more than one folder containing .js files in folder \Commands.
The second and preferred method I want to try to load commands is giving some issues.
Below is the code of what I want to do, however I'm getting an console error Error: Cannot find module '../src/Commands/Moderators/colours.js'
. The colours.js file does exist within that directory. I cannot pin point what the issue is here.
fs.readdirSync("../src/Commands/").forEach(dir => {
const commandfiles = fs.readdirSync(`../src/Commands/${dir}/`).filter(f =>
f.endsWith('.js'));
for (const file of commandfiles) {
const command = require(`../src/Commands/${dir}/${file}`);
console.log(`Loading ${command.name}`, "cmd");
this.commands.set(command.name, command);
Project Structure:
Users/
Jac/
Desktop/
jacbot/
src/
├─ main.js
├─ Structures/
├─ Commands/
│ ├─ Moderation/
│ │ ├─ colours.js
├─ Data/
│ ├─ config.json
├─ Events/
│ ├─ messages.js
Any help would be appreciated.
Upvotes: 0
Views: 655
Reputation: 87
So after much head scratching I figured out. The issue wasn't to do with the readdirSync
method but require
line. It should be ../Commands/${dir}/${file}
opposed to ./Commands/${dir}/${file}
.
The reason is that the code is within a file that is inside another folder within the projects root folder.
Therefore we need to go back one and look for the Commands folder in the root folder. In this case ../
to go back the root folder ./src
and then /commands/folder/file
.
Here is the corrected code block.
fs.readdirSync("./Commands").forEach(dir => {
const commandfiles = fs.readdirSync(`./Commands/${dir}/`).filter(file => file.endsWith('.js'));
for (const file of commandfiles) {
const command = require(`../Commands/${dir}/${file}`);
console.log(`Loading ${command.name}`, "cmd");
this.commands.set(command.name, command);
Upvotes: 0
Reputation:
Because your Commands files are in the src directory, you don't need to leave that directory. Your path should be something like ./Commands
or ./Commands/Moderation
if you're running from the main folder
../
indicates that you're leaving the current directory to go up one
./
is in the current directory
Upvotes: 1