discord.js Command Handler报无法读取name属性错误如何解决
问题原因
报错根源是命令文件的CommonJS导出语法书写错误。
Node.js CommonJS 模块规范中,用于导出模块内容的固定属性为复数形式的exports,你的命令文件中写为module.export(末尾缺少s),会导致require()加载该文件时拿到的返回值为undefined,后续执行command.data.name访问逻辑时,自然会抛出「无法读取undefined的name属性」的类型错误。
修复方案
- 修正所有命令文件的导出语句,将
module.export改为module.exports
修复后的ban命令文件代码如下:module.exports = { data: { name: "ban", description: "Ban an user" }, async execute(interaction){ // 业务逻辑代码 } } - 可选优化:给命令加载流程增加格式校验,避免单个命令文件书写错误导致整个Bot启动崩溃,修改后的index.js命令加载逻辑如下:
client.commands = new Collection(); const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); for(const file of commandFiles){ const command = require(`./commands/${file}`); // 校验命令必要字段是否存在 if (!command?.data?.name || typeof command.execute !== 'function') { console.log(`[警告] 命令文件${file}格式不符合要求,已跳过加载`); continue; } client.commands.set(command.data.name, command) }
注意:检查所有命令文件的字符串引号是否配对,你贴出的代码中description字段的引号存在转义显示不一致的情况,实际编写时需保证前后引号匹配,避免触发额外的语法错误。
内容的提问来源于stack exchange,提问作者YI HAN ZHOU
相关产品推荐
相关产品推荐

