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.
Something like this
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'));
(this assumes that routes are always named MODULENAME.EXPORTEDNAME).
I second what @robertklep said "I would rather have a slow startup with fast request handling than fast startup with slow request handling".
But I strongly recommend against doing a require to handle a request because the first call is synchronous and will block the server, which not only affects the current request, but prevents any other request from being processed. With enough such requests, and your server will stop answering requests.
Basically: preload all the code you will need, but lazy load data (in an asynchronous fashion).
(This is not what you are asking for, but this would be considered bad practice).