Bot无法读取commands目录文件,报ENOTDIR错误求助
Bot命令目录读取失败问题解决
问题描述
开发的Bot初始运行正常,添加功能与命令后,无法读取commands目录下的文件,提示找不到.DS_Store;切换至含JavaScript命令的目录后,仍无法识别确实存在的文件,重新编写代码也未解决。
相关代码
获取文件的代码
const functions = fs.readdirSync("./src/functions").filter(file => file.endsWith(".js")); const eventFiles = fs.readdirSync("./src/events").filter(file => file.endsWith(".js")); const commandFolders = fs.readdirSync("./src/commands"); (async () => { for (file of functions) { require(`./functions/${file}`)(client); } client.handleEvents(eventFiles, "./src/events"); client.handleCommands(commandFolders, "./src/commands"); client.login(process.env.token) })();
报错代码行
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
错误信息
Error: ENOTDIR: not a directory, scandir
./src/commands/.DS_Store
解决方案
问题根源是.DS_Store是Mac系统自动生成的隐藏文件,并非目录,但你的代码将./src/commands下的所有内容都当作目录处理,导致读取非目录文件时触发错误。以下是几种解决办法:
方法一:仅保留目录(推荐)
获取commandFolders时,过滤出真正的目录:const commandFolders = fs.readdirSync("./src/commands", { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name);方法二:直接排除.DS_Store
在获取commandFolders时过滤掉该隐藏文件:const commandFolders = fs.readdirSync("./src/commands").filter(file => file !== ".DS_Store");方法三:在handleCommands中做判断
在读取文件前先确认目标路径是目录:const fullPath = `${path}/${folder}`; // 先判断是否为目录,不是则跳过 if (!fs.statSync(fullPath).isDirectory()) return; const commandFiles = fs.readdirSync(fullPath).filter(file => file.endsWith('.js'));
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

