Node.js: Configuration and routes in a different file

29,291

Solution 1

You can leverage require, and simply pass the app var in as a parameter to a method. It's not the prettiest syntax, nor is it in CoffeeScript, but you should get the idea.

routes.js

module.exports = function (app) {
    // set up the routes themselves
    app.get("/", function (req, res) {
        // do stuff
    });
};

app.js

require("./routes")(app);

If you want to take it a step further, I separate my routes into smaller groups, and in it's own subfolder. (like: routes/auth.js for login/logout, routes/main.js for home/about/contact and so on)

routes/index.js

// export a function that accepts `app` as a param
module.exports = function (app) {
    require("./main")(app);
    // add new lines for each other module, or use an array with a forEach
};

(rename routes.js from before as routes/main.js, the source itself remains the same)

Solution 2

Express 4 simplifies this with the express.Router class.

The other feature to help organize routes is a new class, express.Router, that you can use to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.

The following example creates a router as a module, loads a middleware in it, defines some routes, and mounts it on a path on the main app.

Create a router file named birds.js in the app directory, with the following content:

var express = require('express');
var router = express.Router();

// middleware specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});

// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});

// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

Then, load the router module in the app:

var birds = require('./birds');
app.use('/birds', birds);

The app will now be able to handle requests to /birds and /birds/about, along with calling the timeLog middleware specific to the route.

Solution 3

There are 2 similar question that can help you a lot with this:

How to structure a express.js application?

Nodejs/Expressjs app structure

Share:
29,291
donald
Author by

donald

Updated on July 09, 2022

Comments

  • donald
    donald almost 2 years

    I am starting a new Node.js app and this time, I'm trying to organize the code correctly instead of having everything in the same file.

    I only have a simple setup now at server.coffee:

    express = require 'express'
    app = module.exports = express.createServer()
    
    ## CONFIGURATION ##
    
    app.configure () ->
     app.set 'views', __dirname + '/views'
     app.set 'view engine', 'jade'
     app.use express.bodyParser()
     app.use express.logger('dev')
     app.use express.profiler()
     app.use express.methodOverride()
     app.use app.router
     app.use express.static(__dirname + '/public')
    
    app.configure 'development', () ->
     app.use express.errorHandler({dumpExceptions: true, showStack: true})
    
    app.configure 'production', () ->
     app.use express.errorHandler()
    
    app.get '/', (req,res) ->
      res.render 'index'
        title: 'Express'
    
    ## SERVER ##
    port = process.env.PORT || 3000 
    
    app.listen port, () ->
      console.log "Listening on port" + port
    

    I have some questions regarding that simple code and I know that all the answers depend on the developer but I really want to do it right:

    • Should the server.js file have more than the app.listen? What should be there exactly?
    • Shouldn't all the configurations be in a different file than the routes? How can I remove the app.get to other file and make them work when I run the server.coffee?
    • What exactly should contain the index.coffee that I see in a lot of apps like Hubot?

    I hope someone can give me an answer other than "it depends".

  • alexserver
    alexserver almost 10 years
    thanks @Dominic this is what I was looking for, an advice on how to make an application architecture. expressjs guys should have something like this on their page.
  • fullstacklife
    fullstacklife over 9 years
    I suggest you have a look at the example regarding express.Router() expressjs.com/migrating-4.html#express-router it is very similar to this, but it helped me get my head around this even more.
  • Nick Pineda
    Nick Pineda about 8 years
    The link above is broken.
  • paulsm4
    paulsm4 about 8 years
    @Nick Pineda: the link is expressjs.com/en/guide/migrating-4.html. There's no "#express-router" anchor anymore - you just have to scroll down to "express.Router" ... or "birds.js".