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

如何解决加载JS命令文件时报Error: cannot find module的问题

问题根源

  1. 相对路径不匹配:第一个可行版本中,fs.readdirSync 路径前缀为 ../src/Commands/,但 require 路径前缀为 ../Commands/,说明二者的相对路径计算基准不同。第二段代码中将 require 的路径也加上了 ../src/ 前缀,导致实际寻址路径出错,找不到对应文件。
  2. 缺少文件夹类型过滤:直接用 fs.readdirSync 读取 Commands 目录时,返回结果包含所有子项(含文件、文件夹),如果 Commands 根目录下存在非文件夹内容,会导致后续拼接的子路径无效。另外你报错信息中出现的目录名是 Moderators,但实际目录为 Moderation,也可先检查是否存在拼写错误或者误创建的同名文件夹。

优化实现方案

建议使用 path 模块处理绝对路径,彻底避免相对路径计算错误,同时增加类型过滤逻辑,代码如下:

const fs = require('fs');
const path = require('path');

// 基于当前文件路径拼接Commands目录的绝对路径,无需手动计算相对层级
const commandsRoot = path.join(__dirname, '../Commands');

// 读取目录时携带withFileTypes参数,直接判断子项是否为文件夹
fs.readdirSync(commandsRoot, { withFileTypes: true })
  .filter(dirItem => dirItem.isDirectory())
  .forEach(dirItem => {
    const subDirPath = path.join(commandsRoot, dirItem.name);
    const jsFiles = fs.readdirSync(subDirPath).filter(file => file.endsWith('.js'));

    for (const file of jsFiles) {
      const command = require(path.join(subDirPath, file));
      console.log(`Loading ${command.name}`, "cmd");
      this.commands.set(command.name, command);
    }
  });

方案优势

  • 用绝对路径寻址,完全规避不同文件下相对路径计算错误的问题
  • 自动过滤非文件夹子项,兼容Commands根目录下存在其他文件的场景
  • 所有路径由path.join自动拼接,避免手动拼接字符串导致的拼写、斜杠方向错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:45:04