Express是基于Node.js平台,快速、开放、极简的 Web 开发框架。它常用和核心的api的有,use,get,post,listen。接下来我们简单写一下这些方法的基本实现方法,主要是中间件的原理
const http=require('http');
const slice=Array.prototype.slice;
class LikeExpress {
constructor(arg) {
this.routes={
all:[],
get:[],
post:[]
}
}
register(path){
console.log(arguments,'注册信息')
let info={};
console.log(path,typeof path)
if(typeof path =='string'){
// 如果第一个参数是字符,默认是路由路径
info.path=path;
// 将后面的参数当做中间件放到stack中
info.stack=slice.call(arguments,1)
}else{
info.path='/';
info.stack=slice.call(arguments,0)
}
return info
}
cellectRoutes(arg,type){
// 将中间件推送到all队列中
let middleware=this.register.apply(this,arg);
this.routes[type].push(middleware);
console.log(JSON.stringify(middleware))
}
use(){
this.cellectRoutes(arguments,'all')
}
get(){
this.cellectRoutes(arguments,'get')
}
post(){
this.cellectRoutes(arguments,'post')
}
match(req,res){
let url=req.url;
let method=req.method.toLowerCase();
let currentRoutes=[];
let stacks=[];
// all是根路由,符合所有路径的
currentRoutes=currentRoutes.concat(this.routes.all);
// 将对应请求方法的,合并进去
currentRoutes=currentRoutes.concat(this.routes[method]);
// 筛选符合条件的中间件出来
currentRoutes.forEach((item)=>{
if(url.indexOf(item.path)==0){
stacks=stacks.concat(item.stack)
}
})
return stacks
}
callback(){
return (req,res)=>{
// 实现res.json方法
res.json=(data)=>{
res.setHeader('Content-Type','application/json');
res.end(JSON.stringify(data))
}
let currentStacks=this.match(req,res);
// 一次执行符合条件的方法
this.handle(currentStacks,req,res)
}
}
handle(stacks,req,res){
// 实现next方法
console.log(JSON.stringify(stacks))
console.log(JSON.stringify(this.routes))
const next =()=>{
// 从符合条件的对列中拿出第一个中间件,并执行
let stack=stacks.shift();
if(stack){
stack(req,res,next)
}
}
next()
}
listen(){
// 建立监听
let server=http.createServer(this.callback());
server.listen(...arguments)
}
}
module.exports=()=>{
return new LikeExpress()
}
以上代码就是一个简单的express的实现方法,实现了express的几个核心方法