javascript - 如何优化多个 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 函数指针的事情,但我不知道该怎么做。
解决方案
如果你想要更少的需求和减少,我建议你创建一个文件来导入你的命令并返回一个关联的地图
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);
推荐阅读
- python - 如何在python中将同时具有字符串和int的数据框的列转换为仅int
- javascript - 如何在 NodeJS 中将 DATA 返回到 API
- python - 求最小化矩阵向量乘积标准差的向量排列
- javascript - 自定义四舍五入逻辑
- flutter - 如何在 Flutter 中禁用 RawMaterialButton?
- reactjs - 如何有条件地导入和重新渲染 app.js
- c++ - 前序树遍历和入栈顺序
- tensorflow - 如何在使用张量板查看混淆矩阵的同时绘制混淆矩阵的实际数字和颜色?
- python - 如何使用python比较来自不同图像的对象
- java - Java Web 应用程序每天仅调用 4 次外部 API 的最佳方法(考虑夏令时)