Discord.js v13 机器人无法读取Commands分类子目录命令如何解决
问题原因
fs.readdirSync 原生不支持通配符 * 匹配规则,你传入的 ./src/Commands/*/*.js 会被 Node.js 当做实际存在的路径去扫描,自然找不到对应目录,直接抛出 ENOENT 报错。同时后续 require 路径中使用通配符也是错误用法,Node.js 模块导入不支持通配符匹配。
修复方案(无额外依赖)
先读取 Commands 目录下的所有分类子目录,再逐个遍历子目录内的 .js 命令文件即可,适配全平台路径规则,修改后代码如下:
const fs = require('fs'); const path = require('path'); // 先获取Commands目录下所有分类子目录(Moderation、Fun等) const commandCategories = fs.readdirSync("./src/Commands") // 过滤掉根目录下非目录类型的文件 .filter(category => fs.lstatSync(path.join("./src/Commands", category)).isDirectory()); const commands = []; // 遍历每个分类子目录 for (const category of commandCategories) { // 读取当前分类目录下所有js后缀的命令文件 const commandFiles = fs.readdirSync(path.join("./src/Commands", category)) .filter(file => file.endsWith(".js")); // 逐个加载命令 for (const file of commandFiles) { const cmd = require(path.join("../Commands", category, file)); commands.push(cmd); console.log(`Command ${cmd.name} loaded`); this.commands.set(cmd.name, cmd); } } // 原有slashCommands处理逻辑无需修改,直接沿用 const slashCommands = commands .filter(cmd => ["BOTH", "SLASH"].includes(cmd.type)) .map(cmd => ({ name: cmd.name.toLowerCase(), description: cmd.description, permissions: [], options: cmd.slashCommandOptions, defaultPermission: true }));
如果需要支持更深层级的嵌套子目录,把上述遍历逻辑改成递归遍历即可。
可选方案(使用glob匹配库)
如果不想手写遍历逻辑,可以安装fast-glob库直接用通配符匹配文件:
- 安装依赖:
npm install fast-glob - 修改加载代码:
const glob = require('fast-glob'); // 匹配Commands下所有子目录的js文件 const commandFiles = glob.sync("./src/Commands/**/*.js"); const commands = commandFiles.map(file => { // 转换为当前文件的相对导入路径 const relativePath = file.replace('./src/Commands/', '../Commands/'); return require(relativePath); }); commands.forEach(cmd => { console.log(`Command ${cmd.name} loaded`); this.commands.set(cmd.name, cmd); }); // slashCommands逻辑不变
内容的提问来源于stack exchange,提问作者StackCode
相关产品推荐
相关产品推荐

