-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo06.js
62 lines (58 loc) · 1.31 KB
/
demo06.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
const Koa = require('koa');
const app = new Koa();
const bodyparser = require('koa-bodyparser');
const fs = require('fs');
app.use(bodyparser());
app.use(async(ctx) => {
//读取文件是异步
let html = await getHtml(ctx.url);
ctx.body = html;
})
/**
* @param { string } 访问路由
* @return { string } html
*/
async function getHtml(url) {
let page = '404.html';
console.log(url)
switch (url) {
case '/':
{
page = 'index.html';
break
}
case '/list':
{
page = 'list.html';
break
}
default:
{
page = '404.html';
break
}
}
let html = await render(page);
return html
}
/**
* @param { string } 文件名
* @return { promise } 返回文件
*
*/
function render(page) {
return new Promise((resolve, reject) => {
let pagePath = `./html/${page}`;
console.log(pagePath)
fs.readFile(pagePath, 'utf-8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
})
})
}
app.listen(3000, () => {
console.log("server is running at http://127.0.0.1:3000")
})