Express服务启动常规七步
1. 引用模块
var express=require('express'),
compression=require('compression'),
bodyParser=require('body-parser'),
mongo=require('mongoskin');
2. 实例化express.js对象和其它对象
var app=express();
var db=mongo.db('mongodb://localhost:27017/test',{native_parser:true});
3. 连接数据库(MongoDB,Redis,MySQL等)
var session=require('express-session');
var RedisSession=require('connect-redis')(session);
app.use(session({
store : new RedisStroe(options),
secret : 'express'
}));
4. 配置(模块引擎,文件扩展名等)
a) app.set('view engine','jade');
b) app.set('port',process.env.PORT || 3000);
5. 定义中间件(异常处理,静态文件目录,cookies解析器等)
app.use(bodyParser.json());
6. 定义路由
app.get('/',renderHomePage);
7. 启动服务(指定宿主和端口)
var server=http.createServer(app);
var boot=function(){
server.listen(app.get('port'),function(){
console.info('Express server listening on port ' + app.get('port'));
});
};
var shutdown=function(){
server.close();
}
if(require.main==module){
boot();
}else{
console.info('Running app as a module');
exports.boot=boot;
exports.shutdown=shutdown;
exports.port=app.get('port');
}