This repository has been archived by the owner on Jan 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
100 lines (86 loc) · 2.47 KB
/
app.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var fs = require('fs');
var http = require('http');
var site = require('./config/site.json');
var msgs = require('./config/feedback.json');
var api = require('./routes/api');
var logDirectory = __dirname + '/logs';
if(!fs.existsSync(logDirectory)){ fs.mkdirSync(logDirectory, '0755'); }
var accessLogfile =
fs.createWriteStream(logDirectory + '/access.log', { flags: 'a' });
var errorLogfile =
fs.createWriteStream(logDirectory + '/error.log', { flags: 'a' });
var app = express();
app.use(favicon(__dirname + '/favicon.ico'));
if (app.get('env') === 'development') app.use(morgan('dev'));
if (app.get('env') === 'production') {
app.use(morgan('combined', {stream: accessLogfile}));
}
// Github webhook
app.post('/update_hook', require('./routes/webhook'));
// Get raw body middleware
app.use(function(req, res, next) {
var buffer = [];
var bufferLength = 0;
req.on('data', function (chunk) {
buffer.push(chunk);
bufferLength += chunk.length;
});
req.on('end', function (chunk) {
if (chunk) {
buffer.push(chunk);
bufferLength += chunk.length;
}
req.rawBody = Buffer.concat(buffer, bufferLength);
next();
});
});
// get information
app.use('/api', api);
// 未定义路由
app.use(function(req, res, next) {
var err = {};
err.status = 80001;
next(err);
});
/**
* 错误处理
*/
app.use(function(err, req, res, next) {
if (!err.status) {
var meta = '[' + new Date() + ']' + req.url + '\n';
errorLogfile.write(meta + err.stack + '\n', 'utf-8');
}
// if (app.get('env') === 'development') console.log(err);
if (err.status === 404) {
err.status = 80004;
}
var errcode = err.status || 80005;
res.send({errcode: errcode, errmsg: msgs[errcode]});
});
var port = process.env.PORT || site.port;
app.set('port', port);
var server = http.createServer(app);
server.listen(site.port, function () {
console.log('Sevice is running at ' + site.root + ':' + site.port);
});
server.on('error', function (error) {
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
});