javascriptnode.jsdiscorddiscord.jsslash

TypeError: Cannot read properties of undefined (reading 'toJSON') - Discord.js slash commands


I tried making slash commands today on Discord.js, but my console threw some errors that it cannot read the property toJSON what can be the possible solution to it?

Here are my errors:

~/.../stuff/hazy $ node hazy.js
/storage/emulated/0/stuff/hazy/hazy.js:163
  commands.push(command.data.toJSON());
                             ^

TypeError: Cannot read properties of undefined (reading 'toJSON')
    at Object.<anonymous> (/storage/emulated/0/stuff/hazy/hazy.js:163:30)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v17.9.0

Here is my code:

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token } = require('./config.json');
const fs = require('node:fs');

const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

// Place your client and guild ids here
const clientId = '913559840780091453';
const guildId = '912552644462121050';

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  commands.push(command.data.toJSON());
}

const rest = new REST({ version: '9' }).setToken(token);

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

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

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

Solution

  • Replace

    commands.push(command.data.toJSON());
    

    with

    commands.push(JSON.stringify(command.data));
    

    Thanks to Vincent for helping!