You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Discord Bot报Cannot find module错误,如何排查解决?

错误根因

你报错的核心问题是路径拼接逻辑错误:

  • 你的category变量已经是通过join拼接生成的绝对路径(值类似C:\Users\domri\OneDrive\Desktop\Repositories\Discord Bot\commands\test)
  • 你在require时额外加了./前缀,导致最终路径变成非法格式./C:\xxx\xxx,Node.js无法识别这种混合了相对路径前缀的绝对路径,自然找不到对应模块
  • 额外问题:硬编码/作为路径分隔符,在Windows系统下会导致路径同时出现\和/两种分隔符,增加路径解析失败概率

修复方案

直接修改require的路径拼接逻辑即可,完整修正后的代码如下:

// 确保你已经在文件顶部导入了path模块的join方法:const { join } = require('path');
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => join(source, name)).filter(isDirectory);

getDirectories(join(__dirname, 'commands')).forEach(category => {
  const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));

  for (const file of commandFiles) {
    // 去掉多余的./前缀,改用join统一拼接路径
    const command = require(join(category, file));
    client.commands.set(command.name, command);
    if (command.aliases) {
      for (const alias of command.aliases) {
        client.aliases.set(alias, command.name);
      }
    }
  }
});

内容的提问来源于stack exchange,提问作者Dinosaur Dom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 01:51:03