Discord.js机器人启动报MODULE_NOT_FOUND 找不到指定命令模块如何解决
问题描述
启动自行开发的Discord机器人时出现报错,系统提示无法定位命令所需的模块文件。
命令加载代码
const fs = require('fs'); module.exports = (client, Discord) =>{ const commandFolders = fs.readdirSync('./commands') for(const folder of commandFolders){ const command_files = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js')) for(const file of command_files){ const command = require(`./commands/${folder}/${file}`); if(command.name){ client.commands.set(command.name, command); }else { continue } } } }
完整报错信息
node:internal/modules/cjs/loader:944 throw err; ^ Error: Cannot find module './commands/Fun/8ball.js' Require stack: - C:\Users\Desktop\Discordproject\handlers\command_handler.js - C:\Users\Desktop\Discordproject\index.js at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15) at Function.Module._load (node:internal/modules/cjs/loader:774:27) at Module.require (node:internal/modules/cjs/loader:1013:19) at require (node:internal/modules/cjs/helpers:93:18) at module.exports (C:\Users\Desktop\Discordproject\handlers\command_handler.js:8:25) at C:\Users\famil\Desktop\Discordproject\index.js:11:37 at Array.forEach (<anonymous>) at Object.<anonymous> (C:\Users\Desktop\Discordproject\index.js:10:38) at Module._compile (node:internal/modules/cjs/loader:1109:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10) { code: 'MODULE_NOT_FOUND', requireStack: [ 'C:\\Users\Desktop\\Discordproject\\handlers\\command_handler.js', 'C:\\Users\\Desktop\\Discordproject\\index.js' ] }
项目目录结构

排查与解决方法
- 第一步:修正路径引用逻辑
你的command_handler.js存放在handlers目录下,代码中使用的./commands是相对于当前文件所在目录的相对路径,实际指向的是/handlers/commands,和你存放在项目根目录的commands文件夹路径不匹配。
建议引入path模块,使用绝对路径拼接避免上下文差异导致的路径错误,修正后的代码如下:
const fs = require('fs'); const path = require('path'); module.exports = (client, Discord) =>{ // 拼接得到commands文件夹的绝对路径 const commandsPath = path.join(__dirname, '../commands'); const commandFolders = fs.readdirSync(commandsPath) for(const folder of commandFolders){ const folderPath = path.join(commandsPath, folder); const command_files = fs.readdirSync(folderPath).filter(file => file.endsWith('.js')) for(const file of command_files){ const filePath = path.join(folderPath, file); const command = require(filePath); if(command.name){ client.commands.set(command.name, command); } } } }
- 第二步:排查文件名匹配问题
确认Fun文件夹下的目标文件命名完全符合要求:
- 文件名是
8ball.js,没有多出来的后缀(Windows默认隐藏已知文件后缀,可能实际文件名为8ball.js.txt) - 文件夹名大小写完全匹配,是
Fun而非fun/FUN
- 第三步:确认启动命令的工作目录
执行node index.js启动机器人时,确保当前终端的工作目录是项目根目录(也就是index.js所在的Discordproject文件夹),如果在其他目录启动也会导致相对路径计算错误。
内容的提问来源于stack exchange,提问作者DafamMC
相关产品推荐
相关产品推荐

