Created
May 9, 2018 02:16
-
-
Save LeeeeeeM/0542a8bd0403e38cd00b8cf876d8db72 to your computer and use it in GitHub Desktop.
中间件实现express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function express() { | |
var middlewares = []; | |
var app = function(req, res) { | |
var i = 0; | |
function next() { | |
var task = middlewares[i++]; | |
if (!task) { | |
return; | |
} | |
task(req, res, next); | |
} | |
setTimeout(next); | |
} | |
app.use = function(fn) { | |
middlewares.push(fn); | |
}; | |
return app; | |
} | |
// var http = require('http'); | |
// var app = express(); | |
// http.createServer(app).listen(3000, function() { | |
// console.log('listening 3000'); | |
// }); | |
// function middleware1(req, res, next) { | |
// console.log('middleware1 before next()'); | |
// next(); | |
// console.log('middleware1 after next()'); | |
// res.end('helloworld'); | |
// } | |
// function middleware2(req, res, next) { | |
// console.log('middleware2 before next()'); | |
// next(); | |
// console.log('middleware2 after next()'); | |
// } | |
// function middleware3(req, res, next) { | |
// console.log('middleware3 before next()'); | |
// next(); | |
// console.log('middleware3 after next()'); | |
// } | |
// app.use(middleware1); | |
// app.use(middleware2); | |
// app.use(middleware3); |
Author
LeeeeeeM
commented
Dec 15, 2018
function express() {
const middleWares = []
let i = 0
const context = app.context = {
req: {
list: []
},
res: {
list: []
}
}
function app() {
function next() {
let task = originTask = middleWares[i]
if (i === 0) {
task = function(...args) {
originTask.call(context, ...args)
app.done.call(context, ...args)
}
}
i++
if (task) {
task(context, next)
}
}
setTimeout(next, 0)
}
app.done = function () {
}
app.use = function(fn) {
middleWares.push(fn)
}
return app
}
const app = express()
app.use(function(context, next) {
context.req.list.push(1)
next()
context.res.list.push(1)
})
app.use(function(context, next) {
context.req.list.push(2)
next()
context.res.list.push(2)
})
app.use(function(context, next) {
context.req.list.push(3)
next()
context.res.list.push(3)
})
app.use(function(context, next) {
context.req.list.push(4)
next()
context.res.list.push(4)
})
app.done = function(context) {
console.log(this)
}
app()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment