一个简单的 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
const http = require("http");
const url = require("url");

class Express {
router = {};
constructor() {
this.server = http.createServer((req, res) => {
const pathName = url.parse(req.url).path;
if (pathName !== "/favicon.ico") {
if (
this.router[pathName] &&
typeof this.router[pathName] === "function"
) {
// 回传 req 和 res,实际定义 get/post 路由的地方就能拿到
this.router[pathName](req, res);
} else {
res.writeHead(404, { "content-type": "text/html; charset=UTF-8" });
res.end("路由未定义");
}
}
});
}
get(path, callback) {
this.router[path] = callback;
}
listen(port) {
this.server.listen(port);
}
}

使用

1
2
3
4
5
6
const app = new Express();
app.get("/xxx", (req, res) => {
res.writeHead(200, { "content-type": "text/html; charset=UTF-8" });
res.end("get");
});
app.listen(3000);