-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinitializer.js
86 lines (68 loc) · 1.88 KB
/
initializer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
const fs = require('fs');
const path = require('path');
const log4js = require('log4js');
const express = require('express');
const config = require('./config/config');
function init() {
let app = express();
// 初始化中间件
initMiddleware(app);
// 添加对 ejs 模板引擎的支持
setViews(app);
// 设置静态资源目录
setStatic(app);
// 初始化路由
initRoutes(app);
// 初始化错误路由
initErrorRoutes(app);
// 初始化数据库
initDB(app);
return app;
}
function initMiddleware(app) {
// log4js 日志
let appenders = {};
if (config.environment === 'development') {
appenders[config.project.name] = { type: 'stdout' };
} else if (config.environment === 'production') {
appenders[config.project.name] = {
type: 'dateFile',
filename: '../logs/captcha.log'
};
}
log4js.configure({
appenders: appenders,
categories: {
default: {
appenders: [ config.project.name ],
level: 'debug'
}
}
});
global.logger = log4js.getLogger('stdout');
app.use(log4js.connectLogger(logger, { level: 'debug' }));
}
function setViews(app) {
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
}
function setStatic(app) {
app.use(express.static(path.join(__dirname, 'public')));
}
function initRoutes(app) {
let files = fs.readdirSync('./routes');
for (let f of files) {
let p = path.join(__dirname, 'routes', f);
let router = require(p);
app.use(router);
}
}
function initErrorRoutes(app) {
app.use(function(err, req, res, next){
console.error(err);
res.status(500).send('Something broke!')
})
}
function initDB(app) {}
module.exports.init = init;