前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >nodejs框架express路由的大致原理

nodejs框架express路由的大致原理

作者头像
theanarkh
发布2019-03-06 09:56:16
1.8K0
发布2019-03-06 09:56:16
举报
文章被收录于专栏:原创分享原创分享

昨晚准备洗澡的时候,突然想实现一下express的路由逻辑,但时间有限,只能先写这么多。这个不完全是express的路由原理,只是提供一点思路,具体逻辑可以参考源码,express的路由,好不好不敢说,但是做法挺新颖的,给我一个新的思想。

代码语言:javascript
复制
function Layer(config) {
    if (config.handle instanceof route) {
        this.route = config.handle;
    } else {
        this.handle = config.handle;
    }
}

Layer.prototype = {

}

function route() {
    this.stack = [];
}

route.prototype = {
    dispatch: function(done) {
        if (this.stack.length === 0) {
            return;
        } else {
            this.next(done);
        }
    },
    next: function(done) {
        var layer = this.stack.shift();
        if (!layer) {
            done();
            return;
        }
        layer.handle(this.next.bind(this,done));    
    },
    add: function(fn) {
        this.stack.push(new Layer({handle: fn}));
        return this;
    }
}

function router() {
    this.stack = [];
}

router.prototype = {
    dispatch: function(done) {
        if (this.stack.length === 0) {
            return 
        } else {
            this.next(done);
        }
    },
    next: function(done) {
        var layer = this.stack.shift();
        if (!layer) {
            done();
            return
        }

        if (layer.route) {
            layer.route.dispatch(this.next.bind(this,done));
        }  else {
            layer.handle(this.next.bind(this,done));
        }   
    },
    add: function(fn) {
        this.stack.push(new Layer({handle: fn}));
    },
    route: function(fn) {
        this.stack.push(new Layer({handle: new route().add(fn)}))
    }
}

function app() {
    this.router = new router();
}

app.prototype = {
    initRouter: function() {
        if (this.router) {
            //懒初始化,有时候也不是很好
        }
    },
    use: function(fn) {
        this.router.add(fn);
    },
    route: function(fn) {
        this.router.route(fn);
    },
    start: function() {
        this.router.dispatch(function(){
            console.log('done');
        });
    }
}

var myapp = new app();
myapp.use(function(next) {
    console.log('start');
    next()
});

myapp.use(function(next) {
    console.log('middle');
    next()
});

myapp.route(function(next) {
    console.log('app');
    next()
});
myapp.start()
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-02-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程杂技 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档