首页 > 解决方案 > 如何优化多个 require() 调用?

问题描述

我正在为我公司最重要的服务器制作一个机器人(比如一个不和谐的机器人),对于我的机器人命令,我为每个命令创建了一个文件。

这个想法是,要发送命令,用户必须发送类似“!giveChannelPerms arg1 arg 2 ...”的消息。机器人将解析消息以识别命令(在本例中为 !giveChannelPerms)并执行与命令相关的代码。

问题是对于每个命令,我必须 require() 文件并创建 if {} else if {} else if {} ... 来查找命令,如下面的代码所示。

const giveChannelPerms = require('../cmd/giveChannelPerms');
const removeChannelPerms = require('../cmd/removeChannelPerms');

[...]

if (cmd == "!giveChannelPerms") {
    giveChannelPerms.giveChannelPerms(post, args, db, obj);
} else if (cmd == "!removeChannelPerms") {
    removeChannelPerms.removeChannelPerms(post, args, db, obj);
}

如果我们的机器人只有 2 个命令,则这段代码很好,但是我创建的命令越多,require() 和 if {} else if {} 就会很大。

难道没有更“优化”的方式来做我想做的事吗?我曾想过做一些类似 C 函数指针的事情,但我不知道该怎么做。

标签: javascriptnode.jsmattermost

解决方案


如果你想要更少的需求和减少,我建议你创建一个文件来导入你的命令并返回一个关联的地图

const { giveChannelPerms } = require('../cmd/giveChannelPerms');
const { removeChannelPerms } = require('../cmd/removeChannelPerms');

const cmdMap = new Map();

cmdMap.set('!giveChannelPerms', giveChannelPerms)
cmdMap.set('!removeChannelPerms', removeChannelPerms)

export default cmdMap

然后您将只能导入一次并在文件中无条件使用它:

// Imported multiples functions in one require
const commands = require('../cmd/commands');

// Will execute function associated to cmd string without conditions
commands.get(cmd)(post, args, db, obj);

推荐阅读