我有一个用于我的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/`)
答案 0 :(得分:1)
使用函数封装重复的工作!
您已经走到一半了-您拥有一个可以使用一个目录并列出其中文件的功能。如果您遇到目录,请重复该过程:
function walk(dir, callback) {
fs.readdir(dir, function(err, files) {
if (err) throw err;
files.forEach(function(file) {
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')) {
... your logic here ...
}
});
});
});
}
答案 1 :(得分:0)
这来自Discord.js guide。
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.commands.set(command.name, command);
}
}