如何在Discord.JS命令处理器中添加子文件夹以检测新目录及文件
解决Discord.js命令加载无法识别子文件夹的问题
原代码仅读取commandsDir下的一级文件,无法遍历子文件夹。要实现递归加载,只需利用fs.readdir的recursive选项(Node.js 10.10.0及以上版本支持),同时过滤出合法的命令文件(比如.js后缀),修改后的代码如下:
client.commands = []; const fs = require('fs'); const path = require('path'); // 引入path模块处理路径 fs.readdir(config.commandsDir, { recursive: true }, (err, files) => { if (err) { console.error('读取命令目录失败:', err); return; } files.forEach(async (file) => { // 只处理.js后缀的命令文件,排除文件夹和其他类型文件 if (!file.endsWith('.js')) return; try { // 用path.resolve拼接绝对路径,避免相对路径问题 const filePath = path.resolve(config.commandsDir, file); const props = require(filePath); // 确保命令对象包含必要的name和description字段 if (props.name && props.description) { client.commands.push({ name: props.name, description: props.description, options: props.options || [] }); console.log(`Loaded command: ${props.name}`); } else { console.warn(`跳过无效命令文件 ${file}: 缺少name或description字段`); } } catch (err) { console.error(`加载命令文件 ${file} 失败:`, err); } }); });
关键修改点:
- 添加
{ recursive: true }参数,让fs.readdir递归遍历所有子目录 - 引入
path模块处理文件路径,避免手动拼接路径时出现的错误 - 增加文件后缀过滤,只加载
.js文件,跳过文件夹和非命令文件 - 增加命令字段校验,避免加载不完整的命令对象
- 优化错误提示,明确显示出错的文件路径
内容的提问来源于stack exchange,提问作者Opzo
相关产品推荐
相关产品推荐

