express框架的簡單實現

上面這張圖畫了express的路由處理方式,這也是和koa最大的區別,棧上有一個個的路徑以及處理方法,每一個路徑對應一個層,每一個層裏又會有處理方法或者路由,每一個層裏都有一個next用來傳遞,這至關於一個二維數組。

路由的實現

在使用express的時候,咱們能夠經過以下的方式來註冊路由:javascript

app.get("/",function(req,res){
    res.send("hello world"); 
}); 
複製代碼

實現路由中的"層":

首先要理解一個前面所說的層的概念,簡單點,定義路由的每一個get都是一層,layer.js模塊主要是實現這個層,layer中有兩個參數:path和處理函數java

//layer.js
const pathToRegexp = require('path-to-regexp');
function Layer(path, handler) {
    //path:路徑 handler:處理函數
    this.path = path;
    this.handler = handler;
    this.keys = [];
    this.regexp = pathToRegexp(this.path, this.keys);
}
//判斷層和傳入的路徑是否匹配
Layer.prototype.match = function (path) {
    if (this.path == path) {
        return true;
    }
    if (!this.route) { 
        return path.startsWith(this.path + '/');
    }
    //若是這個Layer是一個路由的層
    if (this.route) {
        let matches = this.regexp.exec(path);
        if (matches) {
            this.params = {};
            for (let i = 1; i < matches.length; i++) {
                let name = this.keys[i - 1].name;
                let val = matches[i];
                this.params[name] = val;
            }
            return true;
        }
    }
    return false;
}
Layer.prototype.handle_request = function (req, res, next) {
    this.handler(req, res, next);
}
Layer.prototype.handle_error = function (err, req, res, next) {
    //錯誤處理函數
    if (this.handler.length != 4) {
        return next(err);
    }
    this.handler(err, req, res, next);
}
module.exports = Layer;
複製代碼

處理請求的路由

router中的index.js:根據文章開始畫的圖,router中應該有一個數組,也就是stack,當咱們調用這裏的route方法的時候會建立一個層(layer)並將path傳進去,並調用route.dispatch交給route去處理,route主要用來建立一個route實例並掛到layer上並執行這個層,這裏還定義了處理中間件和子路由的handle方法以及處理路徑參數的process_params方法.git

const Route = require('./route');
const Layer = require('./layer');
const url = require('url');
const methods = require('methods');
const init = require('./init');
const slice = Array.prototype.slice;
function Router() {
    function router(req, res, next) {
        router.handle(req, res, next);
    }
    Object.setPrototypeOf(router, proto);
    router.stack = [];
    router.paramCallbacks = {};//緩存路徑參數和處理函數
    //加載內置中間件
    router.use(init);
    return router;
}
let proto = Object.create(null);
//建立一個Route實例並添加層
proto.route = function (path) {
    let route = new Route(path);
    let layer = new Layer(path, route.dispatch.bind(route));
    layer.route = route;
    this.stack.push(layer);

    return route;
}
proto.use = function (path, handler) {
    if (typeof handler != 'function') {
        handler = path;
        path = '/';
    }
    let layer = new Layer(path, handler);
    layer.route = undefined;//經過layer有沒有route來判斷是一箇中間件函數仍是一個路由
    this.stack.push(layer);
}
methods.forEach(function (method) {
    proto[method] = function (path) {
        let route = this.route(path);//向Router裏添一層
        route[method].apply(route, slice.call(arguments, 1));
        return this;
    }
});
proto.param = function (name, handler) {
    if (!this.paramCallbacks[name]) {
        this.paramCallbacks[name] = [];
    }
    this.paramCallbacks[name].push(handler);
}
/** * 1.處理中間件 * 2. 處理子路由容器 */
proto.handle = function (req, res, out) {
    let idx = 0, self = this, slashAdded = false, removed = '';
    let { pathname } = url.parse(req.url, true);
    function next(err) {
        if (removed.length > 0) {
            req.url = removed + req.url;
            removed = '';
        }
        if (idx >= self.stack.length) {
            return out(err);
        }
        let layer = self.stack[idx++];
        if (layer.match(pathname)) {
            if (!layer.route) { 
                removed = layer.path;
                req.url = req.url.slice(removed.length);
                if (err) {
                    layer.handle_error(err, req, res, next);
                } else {
                    layer.handle_request(req, res, next);
                }
            } else {
                if (layer.route && layer.route.handle_method(req.method)) {
                    req.params = layer.params;
                    self.process_params(layer, req, res, () => {
                        layer.handle_request(req, res, next);
                    });
                } else {
                    next(err);
                }
            }
        } else {
            next(err);
        }
    }
    next();
}
proto.process_params = function (layer, req, res, out) {
    //路徑參數方法
    let keys = layer.keys;
    let self = this;
    //用來處理路徑參數
    let paramIndex = 0 /**key索引**/, key/**key對象**/, name/**key的值**/, val, callbacks, callback;
    //調用一次param意味着處理一個路徑參數
    function param() {
        if (paramIndex >= keys.length) {
            return out();
        }
        key = keys[paramIndex++];//先取出當前的key
        name = key.name;
        val = layer.params[name];
        callbacks = self.paramCallbacks[name];// 取出等待執行的回調函數數組
        if (!val || !callbacks) {//若是當前的key沒有值,或者沒有對應的回調就直接處理下一個key
            return param();
        }
        execCallback();
    }
    let callbackIndex = 0;
    function execCallback() {
        callback = callbacks[callbackIndex++];
        if (!callback) {
            return param();
        }
        callback(req, res, execCallback, val, name);
    }
    param();
}
module.exports = Router;
複製代碼

router中的route.js:一個路由類,每當get的時候建立一個路由對象,這裏的dispatch是主要的業務處理方法github

const Layer = require('./layer');
const methods = require('methods');
const slice = Array.prototype.slice;
function Route(path) {
    this.path = path;
    this.stack = [];
    this.methods = {};
}
Route.prototype.handle_method = function (method) {
    method = method.toLowerCase();
    return this.methods[method];
}
methods.forEach(function (method) {
    Route.prototype[method] = function () {
        let handlers = slice.call(arguments);
        this.methods[method] = true;
        for (let i = 0; i < handlers.length; i++) {
            let layer = new Layer('/', handlers[i]);
            layer.method = method;
            this.stack.push(layer);
        }
        return this;
    }
});
Route.prototype.dispatch = function (req, res, out) {
    let idx = 0, self = this;
    function next(err) {
        if (err) {
            //錯誤處理,若是出錯就跳過當前路由
            return out(err);
        }
        if (idx >= self.stack.length) {
            return out();
        }
        //取出一層
        let layer = self.stack[idx++];
        if (layer.method == req.method.toLowerCase()) {
            layer.handle_request(req, res, next);
        } else {
            next();
        }
    }
    next();
}
module.exports = Route;    
複製代碼

application.js

這個返回一個Applition類,這裏先定義了一個lazyrouter方法,這個方法主要是用來懶加載,若是不調get的話就沒有初始化的必要因此須要個懶加載;還有listen方法主要用來建立服務器並監聽,這裏面的done主要是處理沒有路由規則和請求匹配。express

const http = require('http');
const Router = require('./router');
const methods = require('methods');
function Application(){
    this.settings = {};//保存參數
    this.engins = {};//保存文件擴展名和渲染函數
}
Application.prototype.lazyrouter = function () {
    if (!this._router) {
        this._router = new Router();
    }
}
Application.prototype.param = function (name, handler) {
    this.lazyrouter();
    this._router.param.apply(this._router, arguments);
}
Application.prototype.set = function (key, val) {
    //設置,傳一個參數表示獲取
    if (arguments.length == 1) {
        return this.settings[key];
    }
    this.settings[key] = val;
}
//定義文件渲染方法
Application.prototype.engine = function (ext, render) {
    let extension = ext[0] == '.' ? ext : '.' + ext;
    this.engines[extension] = render;
}


methods.forEach(function (method) {
    Application.prototype[method] = function () {
        if (method == 'get' && arguments.length == 1) {
            return this.set(arguments[0]);
        }
        this.lazyrouter();
        //此處是爲了支持多個處理函數
        this._router[method].apply(this._router, slice.call(arguments));
        return this;
    }
});
Application.prototype.route = function (path) {
    this.lazyrouter();
    //建立一個路由,而後建立一個layer ,layer.route = route.this.stack.push(layer)
    this._router.route(path);
}
//添加中間件,而中間件和普通的路由都是放在一個數組中的,放在this._router.stack
Application.prototype.use = function () {
    this.lazyrouter();
    this._router.use.apply(this._router, arguments);
}
Application.prototype.listen = function () {
    let self = this;
    let server = http.createServer(function (req, res) {
        function done() {
            //若是沒有任何路由規則匹配的話會走此函數
            res.end(`Cannot ${req.method} ${req.url}`);
        }
        self._router.handle(req, res, done);
    });
    server.listen(...arguments);
}
module.exports = Application;
複製代碼

這裏介紹幾個主要的模塊,所有代碼以及測試用例請見Github數組

相關文章
相關標籤/搜索