Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 504
anonymousfox Avatar asked May 28 '13 04:05

anonymousfox


2 Answers

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...');
});
}
like image 57
sachin Avatar answered Oct 27 '22 11:10

sachin


Typescript

routes/testroute.ts

import { Router } from 'express';

const router = Router();
router.get('/test',() => {
    // Do your stuffs Here
});



export = router;

index.ts

let app = express() 

const routePath = path.join(__dirname, 'routes');

fs.readdirSync(routePath).forEach(async (filename) => {
    let route = path.join(routePath, filename);
    try {
        const item = await import(route);
        app.use('/api', item.default);
    } catch (error) {
        console.log(error.message);
    }
});

app.listen()

like image 28
Aryan Vikash Avatar answered Oct 27 '22 09:10

Aryan Vikash