Home > OS >  Cannot read property of undefined (reading 'push'). Node.JS
Cannot read property of undefined (reading 'push'). Node.JS

Time:11-13

im getting error while using 'node .', the error is "TypeError: Cannot read properties of undefined (reading 'push')

The code is: (handleCommands.js)

const fs = require("fs");
const colors = require("colors");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v10");
module.exports = (client) => {
  client.handleCommands = async () => {
    const commandFolders = fs.readdirSync("./src/commands");
    for (const folder of commandFolders) {
      const commandFiles = fs
        .readdirSync(`./src/commands/${folder}`)
        .filter((file) => file.endsWith(".js"));

      const { commands, commandArray } = client;
      for (const file of commandFiles) {
        const command = require(`../../commands/${folder}/${file}`);
        commands.set(command.data.name, command);
        commandArray.push(command.data.toJSON());
      }
    }

    const clientId = "censored";
    const guildId = "censored";
    const rest = new REST({ version: "10" }).setToken(process.env.TOKEN);
    try {
      console.log("Started refreshing application (/) commands.".yellow);

      await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
        body: client.commandArray,
      });

      console.log("Successfully reloaded application (/) commands.".green);
    } catch (error) {
      console.error(`${error}`.red);
    }
  };
};

The part that using handleCommands.js: (main.js)

require('dotenv').config();
const { TOKEN, Owner, Server, ClientID } = process.env;
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const fs = require('fs');
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandsArray = [];

const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
    const functionFiles = fs
    .readdirSync(`./src/functions/${folder}`)
    .filter(file => file.endsWith('.js'))
    for (const file of functionFiles)
     require(`./functions/${folder}/${file}`)(client);
}

client.handleEvents();
client.handleCommands();
client.login(TOKEN);

This is the error:

handleCommands.js:17
        commandArray.push(command.data.toJSON());
                     ^

TypeError: Cannot read properties of undefined (reading 'push')

Im doing a discord bot, i were expecting to get slash commands but it gives me this error.

CodePudding user response:

i think this is because you are not sending client to handleCommands function

change this :

client.handleCommands();

to this :

 handleCommands(client);

CodePudding user response:

I see! The problem was that in the main.js was not commandArray, there was commandsArray, so the commandArray was undefined.

  • Related