运行Discord Bot执行node .命令时出现MODULE_NOT_FOUND错误求助
Discord Bot运行报错(MODULE_NOT_FOUND)解决方法
问题详情
执行node .启动Discord Bot时触发模块未找到错误:
node:internal/modules/cjs/loader:1042 throw err; ^ Error: Cannot find module 'C:\Users\Michael\Desktop\Discord Bot' at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15) at Module._load (node:internal/modules/cjs/loader:885:27) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12) at node:internal/main/run_main_module:23:47 { code: 'MODULE_NOT_FOUND', requireStack: [] } Node.js v19.3.0
项目核心代码:
- 根目录
main.js:
const Discord = require('discord.js'); const client = new Discord.Client(); const prefix = '?'; const fs = require('fs'); client.commands = new Discord.Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of commandFiles){ const command = require(`./commands/${file}`); client.commands.set(command.name, command); } client.once('ready', () => { console.log('Bot is online!'); }); client.on('message', message =>{ if(!message.content.startsWith(prefix) || message.author.bot) return; const args = message.content.slice(prefix.length).split(/ +/); const command = args.shift().toLowerCase(); if(command === 'ping'){ client.commands.get('ping').execute(message, args); } }); client.login('my magical token');
commands/ping.js:
module.exports = { name: 'ping', description: "this is a ping command!", execute(message, args){ message.channel.send('pong!'); } }
已尝试重装node_modules和Node.js,问题未解决,询问是否需要重建项目及可行的修复方案。
解决步骤
无需重建项目,报错核心是Node无法识别入口文件,按以下顺序排查:
确认命令行工作目录
执行node .前,必须先切换到Bot项目根目录:cd "C:\Users\Michael\Desktop\Discord Bot"目录名含空格时,必须用双引号包裹路径,避免解析错误。
直接指定入口文件执行
跳过node .的自动查找逻辑,直接运行:node main.js这种方式不需要依赖
package.json的配置,更稳定。检查package.json配置(如果存在)
若项目根目录有package.json,确保main字段指向main.js:{ "main": "main.js" }没有该字段的话,Node默认会找
index.js,要么重命名main.js为index.js,要么补充上述配置。修复Discord.js版本兼容问题
你的代码使用new Discord.Client(),如果安装的是Discord.js v14+,必须传入intents参数才能正常启动,否则后续会触发新的报错。修改client初始化代码:const { Client, GatewayIntentBits, Collection } = require('discord.js'); // 必须启用所需的intents const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] }); client.commands = new Collection();Node.js v19.3.0满足Discord.js v14的版本要求(需v16.9+),无需降级。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

