-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
57 lines (48 loc) · 1.21 KB
/
index.js
File metadata and controls
57 lines (48 loc) · 1.21 KB
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
const Koa = require('koa');
const fs = require('fs');
const path = require('path');
const app = new Koa();
app.use(async ctx => {
const target = ctx.request.path;
const ext = path.extname(target).slice(1);
const config = JSON.parse(ctx.cookies.get('config') || "{}");
switch (ext) {
case 'js': {
ctx.set('Content-Type', 'application/javascript');
}
break;
case 'css': {
ctx.set('Content-Type', 'text/css');
}
break;
case 'jpg':
case 'png': {
ctx.set('Content-Type', `image/${ext}`);
}
break;
default:
ctx.set('Content-Type', 'text/html');
}
if (config.type === 'delay' && ext === config.file) {
sleep(config.value);
}
if (target === '/') {
return ctx.body = fs.readFileSync('./index.html');
} else if (fs.existsSync(`.${target}`)) {
return ctx.body = fs.readFileSync(`.${target}`);
} else if (target.endsWith('.html')) {
return ctx.body = fs.readFileSync('./demo/views/index.html');
} else {
ctx.status = 404;
return ctx.body = 'Not Found';
}
});
function sleep(time) {
time = parseInt(time, 10);
if (isNaN(time)) {
return;
}
const end = Date.now() + time;
while (Date.now() < end) {}
}
app.listen(9393);