index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict'
  2. /**
  3. * Module dependencies.
  4. */
  5. const debug = require('debug')('koa-static')
  6. const { resolve } = require('path')
  7. const assert = require('assert')
  8. const send = require('koa-send')
  9. /**
  10. * Expose `serve()`.
  11. */
  12. module.exports = serve
  13. /**
  14. * Serve static files from `root`.
  15. *
  16. * @param {String} root
  17. * @param {Object} [opts]
  18. * @return {Function}
  19. * @api public
  20. */
  21. function serve (root, opts) {
  22. opts = Object.assign({}, opts)
  23. assert(root, 'root directory is required to serve files')
  24. // options
  25. debug('static "%s" %j', root, opts)
  26. opts.root = resolve(root)
  27. if (opts.index !== false) opts.index = opts.index || 'index.html'
  28. if (!opts.defer) {
  29. return async function serve (ctx, next) {
  30. let done = false
  31. if (ctx.method === 'HEAD' || ctx.method === 'GET') {
  32. try {
  33. done = await send(ctx, ctx.path, opts)
  34. } catch (err) {
  35. if (err.status !== 404) {
  36. throw err
  37. }
  38. }
  39. }
  40. if (!done) {
  41. await next()
  42. }
  43. }
  44. }
  45. return async function serve (ctx, next) {
  46. await next()
  47. if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return
  48. // response is already handled
  49. if (ctx.body != null || ctx.status !== 404) return // eslint-disable-line
  50. try {
  51. await send(ctx, ctx.path, opts)
  52. } catch (err) {
  53. if (err.status !== 404) {
  54. throw err
  55. }
  56. }
  57. }
  58. }