【发布时间】:2019-07-19 08:55:41
【问题描述】:
我的 discord 机器人有一个命令处理程序,它搜索文件夹 ./commands/,其中列出了所有 .js 命令。我想清理所有命令,而不是将它们全部放在同一个文件夹中,而是将它们分别放在自己的类别文件夹中。现在的问题是我不知道如何让机器人搜索./commands/ 文件夹的子目录,以在其自己的类别文件夹中找到每个命令。下面是我用来在./commands/ 中搜索的代码。有什么想法让它搜索./commands/ 中的每个目录吗?
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
console.log(`Loading a total of ${files.length} commands.`);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
console.log(`Loading Command: ${props.help.name} ✔`);
client.commands.set(props.help.name, props);
props.conf.aliases.forEach(alias => {
client.aliases.set(alias, props.help.name);
});
});
});
编辑:
这是 jakemingolla 帮助我创造的答案:
function walk(dir, callback) {
fs.readdir(dir, function(err, files) {
if (err) throw err;
files.forEach(function(file) {
console.log(`Loading a total of ${files.length} commands.`);
var filepath = path.join(dir, file);
fs.stat(filepath, function(err,stats) {
if (stats.isDirectory()) {
walk(filepath, callback);
} else if (stats.isFile() && file.endsWith('.js')) {
let props = require(`./${filepath}`);
console.log(`Loading Command: ${props.help.name} ✔`);
client.commands.set(props.help.name, props);
props.conf.aliases.forEach(alias => {
client.aliases.set(alias, props.help.name);
});
}
});
});
});
}
walk(`./commands/`)
【问题讨论】:
标签: javascript discord discord.js