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

首次启动Discord.js极简机器人遭遇ENOTDIR错误求助

问题排查:Discord.js启动时ENOTDIR错误

问题根源

错误提示ENOTDIR: not a directory, scandir 'C:\dev\csupload\src\commands\ping.js'明确说明:你的代码在尝试读取一个文件当作目录处理。大概率是index.js中加载命令的逻辑出错——误对commands目录下的具体文件执行了readdirSync操作,而非正确读取目录下的所有文件。

修复方案

调整index.js里的命令加载逻辑,确保流程是读取commands目录、筛选JS文件、逐个加载。以下是符合官方规范的正确代码示例:

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

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

client.commands = new Collection();
// 指向commands目录的正确路径
const commandsPath = path.join(__dirname, 'commands');
// 读取目录下所有JS文件
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
	const filePath = path.join(commandsPath, file);
	const command = require(filePath);
	// 验证命令结构并存入Collection
	if ('data' in command && 'execute' in command) {
		client.commands.set(command.data.name, command);
	} else {
		console.log(`[WARNING] 命令文件${filePath}缺少必填的"data"或"execute"属性`);
	}
}

// 后续的ready、interactionCreate等事件监听代码...

client.login(token);

关键检查点

  • 确认commandsPath指向的是目录(src/commands),而非某个具体命令文件
  • 用filter(file => file.endsWith('.js'))过滤文件,避免读取非JS文件或子目录(若后续需要子目录,再改用递归遍历逻辑)
  • 对比deploy-commands.js的逻辑,它的文件读取流程是正确的,所以部署命令时能正常执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:30:17