NodeJs : Modularizing routes with ExpressJs

In a previous post I described how to do routing in a NodeJs app with ExpressJs. When the application gets bigger separate routes from our main code is always a good practice. Lets take a look at, how to separate the routes from our main code.
  1. First step is create a separate folder for routes and lets name it as "routes".
  2. Next create index.js file in "routes" directory
    After this step the project structure will look like this.
    
    |--routes
    |  |-index.js
    |--views
    |  |-default.js 
    |--app.js
    

  3. Export routes in index.js file.
    
    exports.index = function(req,res){
        res.render('default',{title:"Home"});
    }
    

  4. Require the routes folder in app.js file
    
    var routes = require('./routes');
    
  5. Provide methods in index.js file to get method of Express when cofiguring routes
    
    app.get('/',routes.index);

In this way we can modularize our routes in node.js app and we can have a clean and understandable code.

3 comments: