Home > Software engineering >  I'm unable to push my bot's slash commands to an array. Why?
I'm unable to push my bot's slash commands to an array. Why?

Time:12-22

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:

const commands = []


fs.readdirSync("./commands").forEach(dir => {
  fs.readdir(`./commands/${dir}`, (err, files) => {
    if (err) throw err;

    const jsFiles = files.filter(file => file.endsWith(".js"));

    if (jsFiles.length <= 0)
      return console.log("[COMMAND HANDLER] - Cannot find any commands!");

    jsFiles.forEach(file => {
      const command = require(`./commands/${dir}/${file}`);
      
      commands.push(command)
      
});
console.log(commands)

module.exports = commands

CodePudding user response:

The readdir function is asynchronous. If you want to use this code with minimal changes then replace it with readdirSync.

Here is the docs with more info: https://nodejs.org/api/fs.html#fsreaddirsyncpath-options

CodePudding user response:

Replace this:

fs.readdirSync("./commands").forEach(dir => {
  fs.readdir(`./commands/${dir}`, (err, files) => {
    if (err) throw err;

    const jsFiles = files.filter(file => file.endsWith(".js"));

    if (jsFiles.length <= 0)
      return console.log("[COMMAND HANDLER] - Cannot find any commands!");

    jsFiles.forEach(file => {
      const command = require(`./commands/${dir}/${file}`);
      
      commands.push(command)
      
});

with this:

const cmdDirectories = fs.readdirSync(`./commands`)
for (const dir of cmdDirectories) {
  const cmdFiles = fs.readdirSync(`./commands/${dir}`).filter(file => file.endsWith(".js"));

  if (cmdFiles.length <= 0)
      return console.log("[COMMAND HANDLER] - Cannot find any commands!");

  for (const file of cmdFiles) {
    const command = require(`./commands/${dir}/${file}`);
    commands.push(command)
  }
}

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.

  • Related