NodeJS 模仿 Express 封装路由
最近才开始学 NodeJs 也不知道为啥就突然对这个很感兴趣,(可能 Java 写烦了😄),感觉用这个开发还是挺快的,而且性能也很好,借此也了解下函数式编程的特点和异步编程的思想。
const http = require("http"); const fs = require("fs"); const path = require("path"); const querystring = require("querystring"); const scores = require("./StudentScore.json"); const template = require("art-template"); http.createServer((req, resp) => { if (req.url.startsWith("/query") && req.method == 'GET') { fs.readFile(path.join(__dirname, "querypage.html"), (err, content) => { if (err) { resp.writeHead(500, { 'Content-Type': 'text/plain;charset=utf8' }); resp.end('服务器错误'); } resp.end(content); }); } else if (req.url.startsWith("/scores")) { let pdata = ''; req.on('data', (ck) => { pdata += ck; }); req.on('end', () => { let obj = querystring.parse(pdata); let result = scores[obj.stunum]; let content = template(path.join(__dirname, "scores.art"), result); resp.end(content); }); } }).listen(9999, () => { console.log('Server is runing on 9999'); });
|
- Express 的方式
通过 const app=express(); 获得一个 app 的对象后面就通过这个来操作

- 手动封装
var url = require('url');
function changeRes(res) {
res.send = function(data) {
res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
res.end(data); } }
var Server = function() {
var G = this;
this._get = {};
this._post = {};
var app = function(req, res) {
changeRes(res);
var pathname = url.parse(req.url).pathname; if (!pathname.endsWith('/')) { pathname = pathname + '/'; }
var method = req.method.toLowerCase();
if (G['_' + method][pathname]) {
if (method == 'post') {
var postStr = ''; req.on('data', function(chunk) {
postStr += chunk; }) req.on('end', function(err, chunk) { req.myBody = postStr; G['_' + method][pathname](req, res); }) } else { G['_' + method][pathname](req, res); } } else { res.end('no router'); } }
app.get = function(string, callback) { if (!string.endsWith('/')) { string = string + '/'; } if (!string.startsWith('/')) { string = '/' + string;
}
G._get[string] = callback;
}
app.post = function(string, callback) { if (!string.endsWith('/')) { string = string + '/'; } if (!string.startsWith('/')) { string = '/' + string;
} G._post[string] = callback;
}
return app;
}
module.exports = Server();
|
- 封装后
const http = require("http"); const url = require("url");
const myApp = require("./model/express-route.js");
http.createServer(myApp).listen(9999, () => { console.log('Running 9999'); });
myApp.get("/express", (req, resp) => { resp.send("模仿 Express 封装路由"); console.log(req); }); myApp.post("/postExpress", (req, resp) => { resp.send("模仿 Express 封装路由"); console.log(req.myBody); });
|
通过这个体会下 Express 的封装
感谢鼓励