index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. const resolve = require('path').resolve;
  6. const assert = require('assert');
  7. const debug = require('debug')('koa-static');
  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 = 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 function *serve(next){
  30. if (this.method == 'HEAD' || this.method == 'GET') {
  31. if (yield send(this, this.path, opts)) return;
  32. }
  33. yield* next;
  34. };
  35. }
  36. return function *serve(next){
  37. yield* next;
  38. if (this.method != 'HEAD' && this.method != 'GET') return;
  39. // response is already handled
  40. if (this.body != null || this.status != 404) return;
  41. yield send(this, this.path, opts);
  42. };
  43. }