Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organizing routes without pre loading the modules in nodejs 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.

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.

like image 288
Rajiv Avatar asked Mar 24 '26 11:03

Rajiv


1 Answers

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).

like image 164
robertklep Avatar answered Mar 27 '26 21:03

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!