简单类express实现

2017-11-07  本文已影响0人  Gary嘉骏

最近公司app的开发又缓慢了下来,于是又重新看node,上一次用node实现个人blog(前端angular)已有两个月了。废话不多说,先谈谈最近对node的新理解。

Node.js® is a JavaScript runtime built onChrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem,npm, is the largest ecosystem of open source libraries in the world.

正文

express的使用

var express = require('express');
var app = express();
app.listen(3000);

能看出引入express时获得的是一个Function,然后调用获得一个对象,最后调用其listen方法去开启服务

由此我们自己可以这样实现

var http=require('http')
var CreateApplication = function(){};
CreateApplication.prototype.listen=function(port,cb){
     var server = http.createServer(function(req,res){
     });
     server.listen(port,cb)
}
var express = function() {
    return new CreateApplication();
} ;

express路由的使用

var express = require('express');
var app = express();
app.use('/',function(req,res){res.end('hello')});
app.listen(3000);

use的方法是对路由的保存

我们自己可以这样实现,对象创建时初始化一个空数组route,然后调用对象的use方法时把路由添加到route里

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

CreateApplication.prototype.use = function(path,fn) {
    this.route.push({
        path:path,
        fn:fn
    })
}

要路由生效的话,只需要在http.createServer里循环route去判断就行

CreateApplication.prototype.listen = function(port,cb) {
    var self = this;
    var server = http.createServer(function(req,res) {
        for(let i=0,len = self.route.length;i<len;i++) {
            let tar = self.route[i];
            if(tar.path == req.url) {
                return tar.fn(req,res);
            }
        }
        res.end('Cannot '+req.method+' '+ req.url);
    });
    server.listen(port,cb)
};

所有代码及验证

var http = require('http');

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

CreateApplication.prototype.use = function(path,fn) {
    this.route.push({
        path:path,
        fn:fn
    })
}

CreateApplication.prototype.listen = function(port,cb) {
    var self = this;
    var server = http.createServer(function(req,res) {
        for(let i=0,len = self.route.length;i<len;i++) {
            let tar = self.route[i];
            if(tar.path == req.url) {
                return tar.fn(req,res);
            }
        }
        res.end('Cannot '+req.method+' '+ req.url);
    });
    server.listen(port,cb)
};

var express = function() {
    return new CreateApplication();
}

var app = express();
app.use('/hello',(req,res) => res.end('hello world'));
app.use('/hey',(req,res) => res.end('hey world'))
app.listen(3001,() => {
    console.log('running on port'+3001);
})

如果觉得文章对你有点用的话,麻烦拿出手机,这里有一个你我都有的小福利(每天一次): 打开支付宝首页搜索“8601304”,即可领红包。谢谢支持

上一篇 下一篇

猜你喜欢

热点阅读