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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:09:03