//koa-logger.js module.exports = async(ctx,next)=>{ const start = new Date().getTime() // 中間件異步處理 await next() const end = new Date().getTime() // 打印出耗時還有長度 console.log(ctx.request.url,end-start,ctx.body.length) }
在server.js中使用app
//server.js const Koa = require('koa') const app = new Koa() const koaLog = require('./koa-logger') // app.use(async(ctx,next)=>{ // ctx.body = 'hello imooc' // }) // 運行結果 // 135642 function delay(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve() },1000) }) } app.use(koaLog) app.use(async(ctx,next)=>{ ctx.body = '1' //下一個中間件 // setTimeout(()=>{ // next() // },2000) await next() ctx.body = ctx.body + '2' }) app.use(async(ctx,next)=>{ ctx.body+= '3' //下一個中間件 await next() ctx.body = ctx.body + '4' }) app.use(async(ctx,next)=>{ ctx.body += '5' await delay() //下一個中間件 await next() ctx.body = ctx.body + '6' }) //啓動應用 app.listen('3000')