express-modular-routes
v1.0.0
Published
Automatically (and recursively) load and mount all files from a directory as routers to Express
Downloads
2
Maintainers
Readme
Express modular Routes
The purpose of this module is to help you organize you Express Routes and to be as less opinionated as possible.
It is very easy to implement into your existing project, and don't have any external dependencies.
Getting started
First you'll need to require it to your existing project that already has an instance of Express.
And then Just tell it which folder to load the routes from, and pass it the instance of express.
const routesLoader = require('express-modular-routes');
...
routesLoader('./controllers', app);
Thats all!
Now, just keep in mind this:
- The routes should be valid Express routes using
express.router
. (example below) - The path passed to Express, will be the name of the file, and the directory relative to the one passed to this module, you'll find examples for this blow too.
Examples
How a valid express router should look like:
const router = require('express').Router();
router.get('/', (req, res) => {
res.send('Hello World!');
});
// Don't forget to export the router!
module.exports = router;
How the route path will be determined:
so lets say you keep all your route's files in a directory called "controllers".
The route path of each file will be equal to its name and path relative to the "controllers" directory.
the only exception is when the file is called index, in this case the route will be equal only to the relative path to the "controllers" folder.
Here are some examples and their output route.
controllers/posts.js // mywebsite.com/posts
controllers/index.js // mywebsite.com/
controllers/movies/index.js // mywebsite.com/movies/
controllers/movies/action.js // mywebsite.com/movies/action/
I hope it is clear enough, and if you have any question, feel free to ask in the issues section.