1. 引用模塊redis
var express=require('express'),mongodb
compression=require('compression'),數據庫
bodyParser=require('body-parser'),express
mongo=require('mongoskin');json
2. 實例化express.js對象和其它對象cookie
var app=express();session
var db=mongo.db('mongodb://localhost:27017/test',{native_parser:true});app
3. 鏈接數據庫(MongoDB,Redis,MySQL等)ui
var session=require('express-session');spa
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');
}