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

如何从文件夹及子文件夹加载Discord.js命令?

修复命令文件夹递归加载问题

你的代码没法正确加载子文件夹里的命令,核心问题有这几个:

  • fs.readdirSync(commandsPath) 默认返回文件名字符串,没有 isDirectory() 方法,判断文件夹的逻辑会直接报错
  • 子文件夹的路径拼接逻辑混乱,导致找不到目标文件
  • 内层循环错误引用了外层的 command 变量,而非当前的 command2
  • 只处理了一层子文件夹,没法遍历更深层级的嵌套

用递归函数实现全文件夹遍历是最稳妥的方案,以下是修复后的完整代码:

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();

// 递归加载所有层级命令的函数
function loadCommands(dirPath) {
  // 读取当前目录,同时获取文件类型信息
  const items = fs.readdirSync(dirPath, { withFileTypes: true });
  
  for (const item of items) {
    const fullPath = path.join(dirPath, item.name);
    if (item.isDirectory()) {
      // 是文件夹就递归进入继续遍历
      loadCommands(fullPath);
    } else if (item.isFile() && item.name.endsWith('.js')) {
      // 是.js文件就加载命令并加入Collection
      const command = require(fullPath);
      // 可选校验:确保命令有必要的结构
      if ('data' in command && 'execute' in command) {
        client.commands.set(command.data.name, command);
      } else {
        console.log(`[警告] ${fullPath} 中的命令缺少data或execute属性`);
      }
    }
  }
}

// 从根命令文件夹开始加载
loadCommands(path.join(__dirname, 'commands'));

关键改进点

  • fs.readdirSync 加上 { withFileTypes: true } 参数,返回的Dirent对象可直接判断文件/文件夹类型
  • 递归函数自动遍历所有嵌套层级的文件夹,不管多深都能处理
  • 路径拼接逻辑完全正确,不会出现文件找不到的情况
  • 增加了简单的命令结构校验,避免加载无效命令

内容的提问来源于stack exchange,提问作者YetNT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:21:03