实现一个express

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
const http = require('http')
const Emitter = require('events')


class WebServer extends Emitter{
constructor(){
super()
this.middlewares = [];
this.context = Object.create(null);
}
use(fn){
if(typeof(fn) === 'function'){
this.middlewares.push(fn)
}
}
listen(...args){
let server = http.createServer(this.callback())
server.listen(...args);
}
callback(){
let that = this;
const handleRequest = (req,res) => {
let context = that.createContext(req,res);

/* 管道执行中间件方式之一[开始] */
// let idx = 0;
// let next = (idx) => {
// if(idx == that.middlewares.length) return context.res.end();
// let fn = that.middlewares[idx];
// idx++
// fn(context)
// next(idx)
// }
// return next(0)
/* 管道执行中间件方式之一[结束] */
/* 管道执行中间件方式之二[开始] */
let start = process.hrtime();
this.middlewares.forEach((fn,idx) =>{
try{
fn(context)
}catch(err){
this.onerror(err)
}
if(idx >= this.middlewares.length - 1){
let end = process.hrtime();
context.res.write(`${(end[0]-start[0])}s,${(end[1]-start[1])/1e6}ms,`)
context.res.end()
}
})
/* 管道执行中间件方式之二[结束] */
}
return handleRequest
}
onerror(err){
console.log(err)
}
createContext(req,res){
this.context.req = req;
this.context.res = res;
return this.context
}
}

var app = new WebServer();
var PORT = 3001;

app.use(ctx => {
ctx.res.write('<p>line 1</p>');
});

app.use(ctx => {
ctx.res.write('<p>line 2</p>');
});

app.use(ctx => {
ctx.res.write('<p>line 3</p>');
});

app.listen(PORT, () => {
console.log(`the web server is starting at port ${PORT}`);
});