node.js - 为什么我的 DJS 机器人找不到我的命令文件夹?
问题描述
我正在为我的 discord.js 机器人制作一个命令处理程序。但是机器人找不到“命令”文件夹。
行代码我有问题:
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
错误信息 :
未捕获的错误:ENOENT:没有这样的文件或目录,scandir './commands'
问题是什么,解决方案是什么?
解决方案
尝试用重音包裹 ./commands:
`./commands`
而不是 './commands' 或在末尾附加一个“/”,有时会有所帮助。
如果您希望处理程序递归搜索所有命令文件,例如您创建子目录来组织您的命令,您可以使用我使用的功能(并推荐):
const fs = require('fs');
const path = require('path');
const rootDir = path.dirname(require.main.filename);
const fileArray = [];
const readCommands = (dir) => {
const __dirname = rootDir;
// Read out all command files
const files = fs.readdirSync(path.join(__dirname, dir));
// Loop through all the files in ./commands
for (const file of files) {
// Get the status of 'file' (is it a file or directory?)
const stat = fs.lstatSync(path.join(__dirname, dir, file));
// If the 'file' is a directory, call the 'readCommands' function
// again with the path of the subdirectory
if (stat.isDirectory()) {
readCommands(path.join(dir, file));
}
else {
const fileDir = dir.replace('\\', '/');
fileArray.push(fileDir + '/' + file);
}
}
};
readCommands('commands');
推荐阅读
- python - 使用列表列表迭代字典
- python-3.x - 在 python 中发出异步 Post 请求
- java - 如何在线程安全模式下以特定数字在 Redis 中启动计数器?
- windows - Xero OAuth 2 令牌
- android - 有时在使用 parceble 创建片段时会发生错误
- r - 如何处理jsonlite中的缺失值?
- python - 如何左外连接使用 SQLAlchemy 关联对象
- android - 如何禁用 FilledTextField 组件?
- json - DeserializerContext.readValue() 抛出输入结束异常
- spring - JPA 规范首先按特定值排序