Open onvno opened 5 years ago
koa static依赖于koa send. static源码理解有几项:
koa static
koa send
static
可以不用关心顺序,因为源码执行如下: 先等待其他中间件完成后才执行koa-static,用了send包
await next() if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return // response is already handled if (ctx.body != null || ctx.status !== 404) return // eslint-disable-line try { await send(ctx, ctx.path, opts) } catch (err) { if (err.status !== 404) { throw err } }
send包作用 读取文件返回ctx.body,其中注意没有使用readFile,使用的是createReadStream
ctx.body
readFile
createReadStream
// stream ctx.set('Content-Length', stats.size) if (!ctx.response.get('Last-Modified')) ctx.set('Last-Modified', stats.mtime.toUTCString()) if (!ctx.response.get('Cache-Control')) { const directives = ['max-age=' + (maxage / 1000 | 0)] if (immutable) { directives.push('immutable') } ctx.set('Cache-Control', directives.join(',')) } if (!ctx.type) ctx.type = type(path, encodingExt) ctx.body = fs.createReadStream(path) return path
koa static
依赖于koa send
.static
源码理解有几项:可以不用关心顺序,因为源码执行如下: 先等待其他中间件完成后才执行koa-static,用了send包
send包作用 读取文件返回
ctx.body
,其中注意没有使用readFile
,使用的是createReadStream