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

Discord机器人注册斜杠命令报错:ENOTDIR,目录存在仍提示非目录

解决Discord机器人斜杠命令注册的ENOTDIR错误

核心问题:变量名拼写错误

你代码里定义了存储命令目录路径的变量commandsDir,但调用fs.readdirSync时误写成了未定义的commandsPath。Node会将未定义的变量解析为undefined,导致fs尝试读取错误的路径,触发ENOTDIR错误。同时,代码里的commands数组未初始化,后续commands.push也会报错,需要补充初始化。

修复步骤

  • 修正变量名:将fs.readdirSync(commandsPath)改为fs.readdirSync(commandsDir)
  • 在循环前添加数组初始化:const commands = [];

修复后的完整代码

const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const fs = require('fs');
const path = require('path');

const commandsDir = path.join(__dirname, 'commands');

if (!fs.existsSync(commandsDir)) {
  console.error(`The 'commands' directory is missing at: ${commandsDir}`);
  process.exit(1);
}

const commands = [];
const commandFiles = fs.readdirSync(commandsDir).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  commands.push(command.data.toJSON());
}

const rest = new REST({ version: '10' }).setToken(token);

(async () => {
  try {
    console.log(`Started refreshing ${commands.length} application (/) commands.`);

    const data = await rest.put(
      Routes.applicationGuildCommands(clientId, guildId),
      { body: commands },
    );

    console.log(`Successfully reloaded ${data.length} application (/) commands.`);
  } catch (error) {
    console.error(error);
  }
})();

额外排查点

  • 确认commands是文件夹而非同名文件:有时会误创建文件代替文件夹,导致路径识别错误
  • 检查目录权限:确保Node进程有读取该目录的权限(虽然你能通过文件管理器访问,但程序权限可能不同)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:57:27