Mark David
Mark David

Reputation: 15

NodeJS - TypeError: Cannot read property 'name' of undefined

I am getting the following error from my code: If you could help me that would be amazing! I am using discord.js!


TypeError: Cannot read property 'name' of undefined at files.forEach.file (/root/eternity-bot/eternity-bot/index.js:21:33) at Array.forEach () at fs.readdir (/root/eternity-bot/eternity-bot/index.js:18:9) at FSReqWrap.oncomplete (fs.js:135:15)


fs.readdir("./commands/", (err, files) => {
  if (err) return console.error(err);
  files.forEach(file => {
    if (!file.endsWith(".js")) return;
    let props = require(`./commands/${file}`);
    console.log(`Loading Command: ${props.help.name}.`);
    bot.commands.set(props.help.name, props);
    props.conf.aliases.forEach(alias => {
      bot.aliases.set(alias, props.help.name);
    })
  });
});

Upvotes: 1

Views: 3464

Answers (2)

NAVIN
NAVIN

Reputation: 3317

TypeError: A TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function.

The possible cause is your props is not loaded correctly and doesn't include any property help, thus accessing property name of unknown property help throws TypeError. Similar to following:

let obj = {
    o1: {
        a: 'abc'
    }
};

obj.o1     // gives {a: 'abc'}, as o1 is property obj which is an object.
obj.o1.a   // gives 'abc', as a is property of o1, which is property of obj.
obj.o2     // undefined, as there's no o2 property in obj.
obj.o2.a   // TypeError as there's no o2 property of obj and thus accessing property a of undefined gives error. 

Upvotes: 3

Rohan Dhar
Rohan Dhar

Reputation: 1837

What is happening is that the code is working perfectly fine, but there seems to be some problem with the exports of your javascript files in the commands folder. Most probably, the help property is not defined in your files.

Upvotes: 1

Related Questions