Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Wyru
Created March 29, 2020 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wyru/926a7bddd6aed7d196a3148650058463 to your computer and use it in GitHub Desktop.
Save Wyru/926a7bddd6aed7d196a3148650058463 to your computer and use it in GitHub Desktop.
Dynamically loads routes for express
// Examples
// "routes/get.js" for a get on "/"
// "route/users/get.js" for a get on "/users"
// "route/users/post.js" for a post on "/users"
// "route/users/$id/post.js" for a post on "/users/:id"
import fs from 'fs-readdir-recursive'
import express from 'express'
const router = express.Router();
const routesLoader = (app) => {
const routes = fs(`${__dirname}/../routes`);
routes.forEach((route) => {
route = route.replace(/\\/g, '/');
let paths = route.split('/')
let action = paths.pop();
action = action.slice(0, -3);
let url = paths.reduce((acc, cur) => `${acc}/${cur}`
, '');
let actionPath = `../routes/${url}/${action}`;
actionPath = actionPath.replace(/\/\//g, '/');
url = url.replace(/\$/g, ':');
router[action](url, require(actionPath).default);
})
app.use(router);
}
export default routesLoader;
import express from 'express';
import utils from './utils';
const app = express();
utils.routesLoader(app);
app.listen(33333, () => {
console.log('listen port 33333');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment