A Simple MVC Framework With Node and Express

I love frameworks. As soon as I dropped my programmer’s ego and learned to embrace well conceived conventions over configuration my development and deployment times felt the benefit. On the other hand, I like understanding what is going on underneath the hood which there is a danger of losing sight of when using a framework.

And this brings me to why I love node.js and express. For me they provide an boilerplate for a framework: the tools I need to quickly build my own conventions.

For sure, it’s pretty easy to build a site with express as it is, but shifting express closer to a MVC setup is simple.
MVC in layman’s terms.

When I used my first MVC framework I got bit bad. It’s not difficult to see why as a pattern it has stood the test of time. And here is all you need to know to start out:

M is for model. A place to define data structures and methods to interact with your data store.
    V is for view. A place to manage everything the end user sees on his or her screen.
    C is for controller. A place to take user requests, bring data from the model and pass it back to the view.

And that’s enough of that for now. Here’s how I arrange my express apps into a basic MVC structure.

First of all I need three folders in the root of my app.

models
    views
    controllers

Now on to the app.js

var express = require(‘express‘);
      ,http = require(‘http‘);
      ,path = require(‘path‘);
      ,app = express();
      ,fs = require(‘fs‘);
// database connection
var mongoose = require(‘mongoose‘);
mongoose.connect(‘mongodb://localhost/mydb‘);
// some environment variables
app.set(‘port‘, process.env.PORT || 3000);
app.set(‘views‘, __dirname + ‘/views‘);
app.set(‘view engine‘, ‘jade‘);
app.use(express.favicon());
app.use(express.logger(‘dev‘));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser(‘your secret here‘));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, ‘public‘)));
// dynamically include routes (Controller)
fs.readdirSync(‘./controllers‘).forEach(function (file) {
  if(file.substr(-3) == ‘.js‘) {
      route = require(‘./controllers/‘ + file);
      route.controller(app);
  }
});
http.createServer(app).listen(app.get(‘port‘), function(){
  console.log(‘Express server listening on port ‘ + app.get(‘port‘));
});

Much of this file is standard if you are generating your app with express, but there are some important lines. Line 5 is where we include the native fs module so we can dynamically read in our controllers. Then in lines 25 to 30 we read in all js files from the controllers directory. Line 13 is pretty important too as it tells express where we want to store our views.

Now whenever we add a js file to our controllers directory we can format it in such a way that it will contain a group of routes. Here is an example that I place in controllers/users.js

var mongoose = require(‘mongoose‘)
var Video = require(‘../models/user‘);
module.exports.controller = function(app) {
/**
 * a home page route
 */
  app.get(‘/signup‘, function(req, res) {
      // any logic goes here
      res.render(‘users/signup‘)
  });
/**
 * About page route
 */
  app.get(‘/login‘, function(req, res) {
      // any logic goes here
      res.render(‘users/login‘)
  });
}

I choose to include my models on a per controller basis (lines 1 to 2), so in my MVC structure they are required in each controller. As modules are cached the first time they are loaded there is no overhead in doing this. Moreover I like having the reference to the models I am using in the file I am using them in.

Line 3 exports all of our routes in the controller function. From here on in you can use the express way of defining routes. But notice that I set my views like this: res.render(‘users/signup‘) which results in the view being loaded from views/users/signup.jade in this app.

Finally, for reference, here is what the model in models/user.js may look like:

Var mongoose = require(‘mongoose‘)
      ,Schema = mongoose.Schema
      userSchema = new Schema( {
          username: String,
          password: String
      }),
User = mongoose.model(‘user‘, userSchema);
module.exports = User;

I like doing things this way because the controller is mediating both the models and the views which for me is the spirit of MVC. There is also a huge organisational win too: if I want to work on users/signup I know I that my model is in models/user.js; my route is in controllers/users.js and my view is in views/users/signup.jade. And that is what makes MVC such a great pattern.

Posted by Tim Roberts Aug 17th, 2013
Tweet

? MongoDB for Developers Certificate

时间: 2024-11-08 15:15:04

A Simple MVC Framework With Node and Express的相关文章

node.js express mvc轻量级框架实践

本文记录的是笔者最近抽私下时间给朋友做的一个时时彩自动下注系统,比较简单,主要也是为了学习一下node.js. 其实逻辑没什么可以深谈的,主要是想说说这套代码结构.结构如下图: js的代码比较难以维护,不清楚大家对于这点是否认同,但这里笔者只说自己的感受,笔者的朋友一开始找到笔者,说玩时时彩,一直盯着玩,会因为贪心会乱来,想做个自动下注系统, 让程序自己玩.一开始,笔者也只想敷衍了事,直接拿node.js+express整了下面这套结构. 基本和express 示例代码没啥两样.但是随着需求的变

Spring - MVC Framework 教程

Spring - MVC Framework Tutorial 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. Spring - MVC Framework Tutorial Advertise

Node.js express获取参数有三种方法

Node.js express获取参数有三种方法 近本人在学习开发NodeJs,使用到express框架,对于网上的学习资料甚少,因此本人会经常在开发中做一些总结. express获取参数有三种方法:官网介绍如下 Checks route params (req.params), ex: /user/:id Checks query string params (req.query), ex: ?id=12 Checks urlencoded body params (req.body), ex

(Spring文档翻译)Part V, the Web 17.1 Spring Web MVC framework介绍

指南文档的这个部分涵盖了Spring框架对表现层(特别是基于Web的表现层)以及WebSocket消息风格的web应用的支持. Spring框架拥有自己的web框架,Spring Web MVC,包含在前面几个章节.之后的几章是关于Spring框架对其他web技术的集成支持,像JSF等. 再之后是Spring框架的MVC porlet 框架. Spring 的MVC框架围绕着DispatcherServlet设计,DispatcherServlet将请求转发给handler,用可配置的handl

Node.js + Express 开发网页, Hello World

摘要:Node.js + Express 开发网页, Hello World 这个参考官方的Guide造著做 http://expressjs.com/guide.html 首先,下安装Node.js 然后,安装ExpressJs 先建立一个hello-world数据夹 在hello-world数据夹中建立package.json数据如下 { "name": "hello-world", "description": "hello wo

[Node.js] express 安装的问题

今天学习express的时候发现安装了express模块但是死活不能使用express命令,在windows上提示内部或者外部命令.在Linux上也不能使用,类似的错误信息.在网上找到了解决方案,记录如下: 版本问题,安装的时候使用命令: npm install -g [email protected]   即可解决问题 刚学习node.js,不知道问题的根源是什么?希望知道的大虾解析一下,拜谢.... ==========================华丽的分割线==============

node.js + express(ejs) + mongodb(mongoose) 增删改实例

刚学node不久,以下是对最近学习的总结,不足的地方还请见谅. node 和 mongodb安装不做为本文讲解,想了解的朋友可以通过一下链接配置环境: node 安装:http://www.infoq.com/cn/articles/nodejs-npm-install-config Win7下MongoDB安装 :http://www.mkyong.com/mongodb/how-to-install-mongodb-on-windows/ MongoDB 安装步骤总结: 1.解压目录到d盘

Node.js, Express的服务器搭建过程的问题

Node.js, Express的服务器搭建过程的问题 Express : node.js 的框架,根据2012年BYvoid的说法,是node.js官方唯一推荐的框架 怎么搭建项目? - 安装nodejs->npm->express - express 的问题: 2017年, express-generator已经被独立成命令行工具了,所以要用 npm install express-generator 这样才能用express命令 怎么启动项目? 启动服务器可以用node app.js,因

node搭建express环境

1.安装好node2.npm安装express插件.npm install express3.express 安装nodejs项目hello.express stooges4.express stooges && cd stooges( stooges是安装的文件夹名)注意每次改完app.js 要重新开命令行窗口 5.npm start(这里需要注意 express 4.x 无法以 node app.js 为启动方式,而是用指令 npm start 作为启动) 访问 http://loca