node.jsexpressroutes

Dynamically load routes with express.js


I am using express.js as a webserver and would like an easy way to separate all the "app.get" and "app.post" functions to separate files. For example, if I would like to specify get and post functions for a login page, I would like to have a login.js file in a routes folder that is dynamically loaded (will automatically add all of the files without having to specify each one) when I run node app.js

I have tried this this solution!, but it isn't working for me.


Solution

  • app.js

    var express=require("express");
    var app=express();
    var fs=require("fs");
    var routePath="./routers/"; //add one folder then put your route files there my router folder name is routers
    fs.readdirSync(routePath).forEach(function(file) {
        var route=routePath+file;
        require(route)(app);
    });
    app.listen(9123);
    

    I have put below two routers in that folder

    route1.js

    module.exports=function(app){
      app.get('/',function(req,res){
         res.send('/ called successfully...');
      });
    }
    

    route2.js

    module.exports=function(app){
    app.get('/upload',function(req,res){
      res.send('/upload called successfully...');
    });
    }