手写expres

// const express = require('express')
// const app = express()
// app.get('/',function(req,res){
//     res.end('我是根目录')
// })
// app.get('/good',function(req,res){
//     res.end('oh you are good')
// })
// app.listen('40087',function(){
//     console.log('正在监听40087')
// })
新建一个js模仿express框架,去完成一个自己的express框架,比如下面的这个js文件我们暂且命名为self.js
const myExpress = require('./self封装的express.js')
const app = myExpress()
app.get('/',function(req,res){
    res.end('我是根目录')
})
app.get('/good',function(req,res){
    res.end('oh you are good')
})
app.listen('40087',function(){
    console.log('正在监听40087')
})
新建一个js文件《self封装的express.js》
 
const http = require('http')
const url = require('url')
let routes = []
class myExpress{
    get(path,handle){
        routes.push({path,handle})
    }
    listen(){
        const server = http.createServer(function(req,res){
            const {pathname} = url.parse(req.url)
            console.log(pathname)
            routes.find((p)=>{
                return p.path == pathname
            }).handle(req,res)
        })
        server.listen(...arguments)
    }
}
module.exports = function(){
    return new myExpress()
}
其实这里面我们用到一个发布订阅模式,首先利用get方法将所有的接口把这些接口还有回调函数push到数组中,构造函数提供了一个listen方法暴漏在外面,我们在app.listen()调用的时候,我们就会将数组里面的回调执行(如果接口,方法对上的话),其实这里面就是一个发布订阅模式。
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/MDGE/p/12541189.html