我会使用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)
您可以在this repl 找到一个工作演示(带字符串)。