Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to organize myapp/routes/*

Using latest stable node.js and express from npm, I've created my first express project.

The default generated app defines routes/index.js, which contains a single route that renders the default index view.

I immediately assumed I could add other .js files to the routes/ folder and they would be included. This didn't pan out. Only routes/index.js is ever included. Adding additional routes to routes/index.js works fine.

What is the proper way to define and organize Express routes, following the structure provided by the express project generator?


The answer, paraphrasing the article at DailyJS:

Given the following routes:

app.get('/', function() {}); app.get('/users', function() {}); app.get('/users/:id', function() {}); 

... Create the following files:

routes/ ├── index.js ├── main.js └── users.js 

Then, inside of routes/index.js:

require('./main'); require('./users'); 

For each new group of related routes, create a new file in routes/ and require() it from routes/index.js. Use main.js for routes that don't really fit in the other files.

like image 250
Gabriel Bauman Avatar asked Jan 27 '12 00:01

Gabriel Bauman


People also ask

How do I Group A route in node JS?

You can use an npm moduleYou can group your middlewares as an array and pass it to the express-inject-middleware... Show activity on this post. in express 4 to grouping your routes, you should create some changes : seperate route files in multiple files like admin and front.

What is a node route?

What is routing? To start with routing in Node. js, one needs to know what is routing and its purpose. The route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern.


1 Answers

I prefer dynamically loading routes instead of having to manually add another require each time you add a new route file. Here is what I am currently using.

var fs = require('fs');  module.exports = function(app) {     console.log('Loading routes from: ' + app.settings.routePath);     fs.readdirSync(app.settings.routePath).forEach(function(file) {         var route = app.settings.routePath + file.substr(0, file.indexOf('.'));         console.log('Adding route:' + route);         require(route)(app);     }); } 

I call this when the application loads, which then requires all files in the routePath. Each route is setup like the following:

module.exports = function(app) {     app.get('/', function(req, res) {         res.render('index', {             title: 'Express'         });     }); } 

To add more routes, all you have to do now is add a new file to the routePath directory.

like image 190
Timothy Strimple Avatar answered Sep 16 '22 21:09

Timothy Strimple