onvno / pokerface

日常技术文章阅读整理
3 stars 0 forks source link

20190523 - koa static && koa send #29

Open onvno opened 5 years ago

onvno commented 5 years ago

koa static依赖于koa send. static源码理解有几项:

  1. 可以不用关心顺序,因为源码执行如下: 先等待其他中间件完成后才执行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
      }
    }
  2. send包作用 读取文件返回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