Node.js使用fs.readdirSync无法读取Commands目录下子文件夹内的.js文件
解决方案
你当前的代码仅读取commands目录的一级内容,没有处理子文件夹,所以无法加载子目录内的js文件,可通过递归遍历目录的方式解决,完整可运行代码如下:
// 需提前引入path模块处理路径 const fs = require('fs'); const path = require('path'); // 请根据你的实际文件位置调整commands目录路径 // 若当前代码在bot文件夹下的index.js中,路径改为 path.join(__dirname, 'commands') 即可 const commandsRootPath = path.join(__dirname, '../main/Commands'); // 递归遍历收集所有js命令文件 function scanCommands(dirPath) { const dirEntries = fs.readdirSync(dirPath, { withFileTypes: true }); let jsFileList = []; for (const entry of dirEntries) { const fullEntryPath = path.join(dirPath, entry.name); if (entry.isDirectory()) { // 递归读取子文件夹 jsFileList = jsFileList.concat(scanCommands(fullEntryPath)); } else if (entry.isFile() && entry.name.endsWith('.js')) { jsFileList.push(fullEntryPath); } } return jsFileList; } const allCommandFiles = scanCommands(commandsRootPath); // 加载所有命令 allCommandFiles.forEach(filePath => { const cmd = require(filePath); console.log(`Command ${cmd.name} loaded`); this.commands.set(cmd.name, cmd); });
简化写法(Node.js >= v18.17.0 支持)
你也可以直接使用fs.readdirSync自带的递归参数简化代码:
const fs = require('fs'); const path = require('path'); const commandsRootPath = path.join(__dirname, '../main/Commands'); const allCommandFiles = fs.readdirSync(commandsRootPath, { recursive: true }) .filter(item => item.endsWith('.js')) .map(item => path.join(commandsRootPath, item)); allCommandFiles.forEach(filePath => { const cmd = require(filePath); console.log(`Command ${cmd.name} loaded`); this.commands.set(cmd.name, cmd); });
注意事项
- 优先使用
path.join拼接路径,可自动适配不同操作系统的路径分隔符,避免手动拼接字符串出现的路径错误 - 确保所有命令文件都正确导出
name属性,否则加载时会打印异常 - 可根据你的实际项目入口文件位置,调整
commandsRootPath的路径参数
内容的提问来源于stack exchange,提问作者Jasme
相关产品推荐
相关产品推荐

