运行Discord.js代码报EISDIR: illegal operation on a directory错误如何解决
错误根因
你代码中调用了fs.readFileSync()读取./cmd目录,该API仅支持读取单个文件,尝试读取目录时就会抛出EISDIR: illegal operation on a directory, read错误。同时你的代码还存在另外两处逻辑错误:
- 遍历文件名数组误用
for...in语法,会拿到数组索引而非文件名本身 - 读取的是
./cmd目录的文件,但require时写死了./commands/路径,两边目录不匹配会导致模块找不到报错 - 同步方法
console.log()前无需加await,属于冗余语法
修复方案
直接替换指令加载部分的代码即可,完整修正后的逻辑如下:
const { Client, Intents, Collection } = require('discord.js') const config = require('./config.json') const fs = require('fs') const path = require('path') // 新增path模块处理路径,避免相对路径兼容性问题 const bot = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES ] }) bot.commands = new Collection() // 修正1:用fs.readdirSync读取目录下的文件列表,开启withFileTypes方便过滤子目录 const cmdDir = './cmd' const cmdFiles = fs.readdirSync(cmdDir, { withFileTypes: true }) .filter(item => item.isFile() && item.name.endsWith('.js')) // 仅保留JS后缀的普通文件 for (const file of cmdFiles) { // 修正2:用for...of遍历拿到实际文件对象 const cmd = require(path.join(cmdDir, file.name)) // 修正3:路径和读取的目录统一,避免路径写错 bot.commands.set(cmd.help.name, cmd) } bot.once("ready", () => { console.log('Bot is ready!') }) bot.on("messageCreate", async message => { if(message.author.bot) return; var prefix = config.prefix if(!message.content.startsWith(prefix)) return; var array = message.content.split(" "); var command = array[0]; const data = bot.commands.get(command.slice(prefix.length)) if(!data) return; var args = array.slice(1) try { await data.run(bot, message, args) } catch(e) { await message.channel.send(e) console.log(e) } }) bot.login(config.token)
内容的提问来源于stack exchange,提问作者Youri_Miner
相关产品推荐
相关产品推荐

