Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
I'm unable to push my bot's slash commands to an array. Why?

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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!