When I try to push my bot’s slash commands to an array which I want to use to register my commands, it doesn’t seem to get pushed, as when I console.log
the array, it returns an empty array. But when I log each command individually, it logs properly. Why?
Here is the code I use to push my bot’s commands to the array:
JavaScript
x
22
22
1
const commands = []
2
3
4
fs.readdirSync("./commands").forEach(dir => {
5
fs.readdir(`./commands/${dir}`, (err, files) => {
6
if (err) throw err;
7
8
const jsFiles = files.filter(file => file.endsWith(".js"));
9
10
if (jsFiles.length <= 0)
11
return console.log("[COMMAND HANDLER] - Cannot find any commands!");
12
13
jsFiles.forEach(file => {
14
const command = require(`./commands/${dir}/${file}`);
15
16
commands.push(command)
17
18
});
19
console.log(commands)
20
21
module.exports = commands
22
Advertisement
Answer
Replace this:
JavaScript
1
16
16
1
fs.readdirSync("./commands").forEach(dir => {
2
fs.readdir(`./commands/${dir}`, (err, files) => {
3
if (err) throw err;
4
5
const jsFiles = files.filter(file => file.endsWith(".js"));
6
7
if (jsFiles.length <= 0)
8
return console.log("[COMMAND HANDLER] - Cannot find any commands!");
9
10
jsFiles.forEach(file => {
11
const command = require(`./commands/${dir}/${file}`);
12
13
commands.push(command)
14
15
});
16
with this:
JavaScript
1
13
13
1
const cmdDirectories = fs.readdirSync(`./commands`)
2
for (const dir of cmdDirectories) {
3
const cmdFiles = fs.readdirSync(`./commands/${dir}`).filter(file => file.endsWith(".js"));
4
5
if (cmdFiles.length <= 0)
6
return console.log("[COMMAND HANDLER] - Cannot find any commands!");
7
8
for (const file of cmdFiles) {
9
const command = require(`./commands/${dir}/${file}`);
10
commands.push(command)
11
}
12
}
13
This solution was found purely by experimentation, I do not know how/why this worked. If someone does know how/why this worked, please leave a comment.