Dynamically load routes using express.js

I use express.js as a web server and would like to easily separate all the functions of "app.get" and "app.post" to separate the files. For example, if I wanted to specify the get and post functions for the login page, I would like to have the login.js file in the dynamically loaded routes folder (it will automatically add all the files without specifying each of them) when I run node app.js

I tried this solution ! But it does not work for me.

+4
source share
3 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 installed below two routers in this 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...'); }); } 
+14
source

As a result, I used a recursive approach for reading code and asynchronous code:

 // routes processRoutePath(__dirname + "/routes"); function processRoutePath(route_path) { fs.readdirSync(route_path).forEach(function(file) { var filepath = route_path + '/' + file; fs.stat(filepath, function(err,stat) { if (stat.isDirectory()) { processRoutePath(filepath); } else { console.info('Loading route: ' + filepath); require(filepath)(app, passport); } }); }); } 

This can be made more reliable by checking the correct file extensions, etc., but I keep my route folder clean and don't want the added complexity

0
source

With this approach, there is no need to write routes manually. Just set up a directory structure such as URL paths. An example route is located in /routes/user/table/table.get.js , and the API route will be /user/table .

 import app from './app' import fs from 'fs-readdir-recursive' import each from 'lodash/each' import nth from 'lodash/nth' import join from 'lodash/join' import initial from 'lodash/initial' const routes = fs(`${__dirname}/routes`) each(routes, route => { let paths = route.split('/') // An entity has several HTTP verbs let entity = `/api/${join(initial(paths), '/')}` // The action contains a HTTP verb let action = nth(paths, -1) // Remove the last element to correctly apply action paths.pop() action = `./routes/${join(paths, '/')}/${action.slice(0, -3)}` app.use(entity, require(action)) }) 

Route example:

 import { Router } from 'express' import Table from '@models/table.model' const routes = Router() routes.get('/', (req, res, next) => { Table .find({user: userIdentifier}) .select('-user') .lean() .then(table => res.json(table)) .catch(error => next(error)) }) module.exports = routes 
0
source

Source: https://habr.com/ru/post/1483078/


All Articles