如何为Discord.JS命令处理器实现子文件夹命令加载功能
实现Discord.JS命令处理器子文件夹加载功能
修改思路
你可以在原有逻辑的基础上增加一层文件类型判断,先读取commands目录下的所有条目,区分子文件夹和直接存放的命令文件,子文件夹再单独遍历读取内部的JS文件即可,同时兼容原有目录结构。
完整修改后代码
const fs = require('fs'); const commandsPath = './commands'; // 命令集合,和你原有的逻辑保持一致 const commands = new Collection(); // 记得保留你原来的Discord.js Collection引入 // 公共命令加载方法,抽离避免重复代码 function loadCommand(fileName, dirPath) { try { const loadedCommand = require(`${dirPath}/${fileName}`); commands.set(loadedCommand.name, loadedCommand); for(const alias of loadedCommand.aliases || []) commands.set(alias, { ...loadedCommand, alias: true }); logger.info(`Loaded command ${loadedCommand.name} (${dirPath}/${fileName})`); } catch (error) { logger.error(`Failed to load command ${fileName} (${dirPath}). **Please report the following error:**`); logger.error(error); } } // 读取commands目录下的所有条目,带文件类型标识 const commandEntries = fs.readdirSync(commandsPath, { withFileTypes: true }); for (const entry of commandEntries) { // 兼容根目录直接存放的命令文件 if (entry.isFile() && entry.name.endsWith('.js')) { loadCommand(entry.name, commandsPath); continue; } // 遍历子文件夹内的命令文件 if (entry.isDirectory()) { const subDirPath = `${commandsPath}/${entry.name}`; const subCommandFiles = fs.readdirSync(subDirPath).filter(file => file.endsWith('.js')); for (const commandFile of subCommandFiles) { loadCommand(commandFile, subDirPath); } } }
扩展与注意事项
- 上述代码仅支持一级子文件夹,如果需要支持无限层级的嵌套分类,可以把读取逻辑替换为递归实现,示例如下:
function loadCommandsRecursive(dirPath) { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); for (const entry of entries) { const fullEntryPath = `${dirPath}/${entry.name}`; if (entry.isDirectory()) { loadCommandsRecursive(fullEntryPath); } else if (entry.isFile() && entry.name.endsWith('.js')) { loadCommand(entry.name, dirPath); } } } // 调用方法替换原有遍历逻辑即可 loadCommandsRecursive(commandsPath);
- 子文件夹命名无特殊限制,可按功能自定义如
moderation(管理类)、fun(娱乐类)、utility(工具类)等 - 原有命令文件的导出格式不需要做任何修改,和你之前的写法完全兼容
- 如果你的项目使用ES模块规范,将
require替换为对应的动态import逻辑即可
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

