This repository has been archived by the owner on Mar 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
98 lines (71 loc) · 2.58 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
// 应用程序入口
const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config');
const toolkit = require('./toolkit');
// 检查命令行参数
if (process.argv[2]) {
// 允许通过`node app.js --stop`杀死进程
if (process.argv[2].toLowerCase() === '--stop') {
let pid_file_path = path.join(config.CACHE_PATH, 'PID');
let pid = parseInt(fs.readFileSync(pid_file_path).toString());
console.log('Evergarden API service is shutting down.');
process.kill(pid, 'SIGTERM');
fs.unlinkSync(pid_file_path);
process.exit();
}
// 允许通过`node app.js --clean`来清理缓存目录
if (process.argv[2].toLowerCase() === '--clean') {
toolkit.cleanCache();
return;
}
}
// 确保缓存文件夹可用
['/', '/list', '/book', '/image'].forEach((dir) => {
let dirpath = path.join(config.CACHE_PATH, dir);
if (!fs.existsSync(dirpath) || !fs.lstatSync(dirpath).isDirectory()) {
fs.mkdirSync(dirpath);
}
});
// 将进程ID写入缓存目录中的PID文件
fs.writeFileSync(path.join(config.CACHE_PATH, 'PID'), process.pid);
// Express路由
const app = express();
// Body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 待添加的密钥检查功能
app.use((req, res, next) => {
next();
});
// CORS
app.use((req, res, next) => {
res.header({
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': req.headers.origin || '*',
'Access-Control-Allow-Headers': 'X-Requested-With',
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
});
next();
});
// 静态文件
app.get(/.*(.jpg)|(.jpeg)/, (req, res) => {
res.send(__dirname + req.path);
});
// 将定义了middleware函数的模块加入路由
fs.readdirSync(__dirname).forEach((filename) => {
if (!filename.match(/.js$/i)) return;
let middleware = require(path.join(__dirname, filename)).middleware;
if (middleware && typeof middleware === 'function') {
let route = '/' + filename.replace(/.js$/i, '');
app.all(route, middleware);
}
});
// 启动服务器
app.listen(config.PORT, () => {
console.log(`Evergarden API service is running at port ${config.PORT}.`);
});
// 每隔config.CACHE_EXPIRATION_MS中指定的时间清理缓存
setInterval(toolkit.cleanCache, config.CACHE_EXPIRATION_MS);