在不预先加载Node.js Express中的模块的情况下组织路由 [英] Organizing routes without pre loading the modules in nodejs express
问题描述
当前,Express框架中的路由要求先加载模块.但这在有数百个模块的现实生活场景中并不高效.我只想加载所需的模块.有没有一种方法可以在不预加载模块的情况下定义到目标模块的路由.
Currently the routing in Express framework requires the module to be loaded before. But that would not be efficient in real life scenarios where there are hundreds of module. I would like to load only the module that is needed. Is there a way where I can define a route to a target module without pre loading the module.
类似这样的东西
app.get('user/showall','user.list');
app.get('user/showall', 'user.list');
因此,我希望仅在特定请求需要加载用户模块时才加载用户模块.
So I would like user module to be loaded only when that particular request needs it to be loaded.
推荐答案
我宁愿使用快速请求处理来缓慢启动,也不愿使用缓慢请求处理来快速启动,因为必须在运行时加载模块.
I would rather have a slow startup with fast request handling than fast startup with slow request handling because modules have to be loaded at runtime.
但是,如果您确实需要,可以创建一个中间件来实现这种行为(完全未经测试):
But if you really want, you could create a middleware to implement such behaviour (totally untested):
var lazyload = function(route) {
var s = route.split('.');
var mod = s[0];
var exp = s[1];
return function(req, res, next) {
require(mod)[exp](req, res);
};
};
...
app.get('user/showall', lazyload('user.list'));
(这假定路由始终被命名为 MODULENAME.EXPORTEDNAME
).
(this assumes that routes are always named MODULENAME.EXPORTEDNAME
).
这篇关于在不预先加载Node.js Express中的模块的情况下组织路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!