node.js - 带有子分类文件夹的命令处理程序
问题描述
这是我当前使用的命令处理程序,它按预期工作。
try {
let ops = {
active: active
}
let commandFile = require(`./commands/${cmd}.js`)
commandFile.run(client, message, args, ops);
} catch (e) {
console.log(e);
}
但正如您所看到的,它只是读入命令文件夹并.js
从那里提取文件。
我想要做的是为了我自己的“强迫症”目的对命令进行子分类,这样我就可以更好地跟踪它们。
这个命令处理程序有什么办法吗?
另外,我已经尝试过discord.js-commando
,但我个人并不喜欢它使用的命令结构。
解决方案
我会使用这个require-all
包。
假设您有如下文件结构:
commands:
folder1:
file1.js
folder2:
subfolder:
file2.js
您可以使用require-all
来完全要求所有这些文件:
const required = require('require-all')({
dirname: __dirname + '/commands', // Path to the 'commands' directory
filter: /(.+)\.js$/, // RegExp that matches the file names
excludeDirs: /^\.(git|svn)|samples$/, // Directories to exclude
recursive: true // Allow for recursive (subfolders) research
});
上面的required
变量将如下所示:
// /*export*/ represents the exported object from the module
{
folder1: { file1: /*export*/ },
folder2: {
subfolder: { file2: /*export*/ }
}
}
为了获得您需要使用递归函数扫描该对象的所有命令:
const commands = {};
(function searchIn(obj = {}) {
for (let key in obj) {
const potentialCommand = obj[key];
// If it's a command save it in the commands object
if (potentialCommand.run) commands[key] = potentialCommand;
// If it's a directory, search recursively in that too
else searchIn(potentialCommand);
}
})(required);
当您要执行命令时,只需调用:
commands['command-name'].run(client, message, args, ops)
你可以在这个repl中找到一个工作演示(带字符串) 。
推荐阅读
- list - 如何在 Python 中将所有对象添加到列表中而不在 for 循环之前使用空列表?
- c++ - 为什么以下两个代码片段会导致 MSVC 的编译输出不同,而 gcc 的编译输出相同?
- android - kotlin-stdlib-jdk 依赖的目的是什么?
- mysql - 如何在 docker 上远程访问 mariadb?
- c# - 对象属性上的自定义扩展方法以返回 DefaultValue
- node.js - Heroku 在构建结束时没有显示我的应用程序
- python - Python:如何在使用 dynamodb 排序后获得位置/排名?
- c - 如何在不使用任何内置函数的情况下将整数转换为 c 字符串,反之亦然和其他数据类型?
- excel - 隐藏 For 循环中每个实例发生的保存窗口
- php - Symfony 5, How to display in a template, a variable where the current user is affiliated with a ManyToMany relations