I like the structure of Model View Controller (MVC) and I wanted to apply it to my Node.js projects.
I’ve written previous articles about Node using Jade Templates with Express, but I didn’t go into much details about code organization; let’s do that now.
MVC implementation with Node.js
Structure wise, here is my preference:
- /
- config
- controllers
- models
- public
- css
- views
- controllerName
- index.jade
- controllerName
- app.js
- routes.js
In the above structure, I create one file per controller, model, and a sub folder in the views directory to hold my Jade jQuery template.
App.js and Route.js Setup
Example app.js setup
[code]
var express = require(‘express’);
var app = module.exports = express.createServer();
var config = require(‘./config/config’);
// Configuration, defaults to jade as the view engine
app.configure(function(){
app.set(‘views’, __dirname + ‘/views’);
app.set(‘view engine’, ‘jade’);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + ‘/public’));
});
app.configure(‘development’, function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.listen(80, function(){
console.log(“Express server listening on port 80”);
});
module.exports.app = app;
routes = require(‘./routes’);
[/code]
The above code sets up Express and Jade as the templating engine, initializes the web server and loads the routes.js file.
Example routes.js setup
[code]
app = module.parent.exports.app;
/* require your controllers here */
var homeController = require(‘./controllers/home’);
var userController = require(‘./controllers/user’);
app.get(‘/’, homeController.index);
app.get(‘/users’, userController.index);
app.get(‘/users/detail’, userController.detail);
[/code]
This instantiates two controllers: home and user. Then one route is created for / that calls the index function in the home controller and two routes are created for the user controller: index and detail.
Hopefully this is a good structure to get you started with using MVC, Express.js, and Jade templates.