You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.2 KiB

  1. /*!
  2. * Connect - static
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var send = require('send')
  11. , utils = require('../utils')
  12. , parse = utils.parseUrl
  13. , url = require('url');
  14. /**
  15. * Static:
  16. *
  17. * Static file server with the given `root` path.
  18. *
  19. * Examples:
  20. *
  21. * var oneDay = 86400000;
  22. *
  23. * connect()
  24. * .use(connect.static(__dirname + '/public'))
  25. *
  26. * connect()
  27. * .use(connect.static(__dirname + '/public', { maxAge: oneDay }))
  28. *
  29. * Options:
  30. *
  31. * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0
  32. * - `hidden` Allow transfer of hidden files. defaults to false
  33. * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true
  34. * - `index` Default file name, defaults to 'index.html'
  35. *
  36. * @param {String} root
  37. * @param {Object} options
  38. * @return {Function}
  39. * @api public
  40. */
  41. exports = module.exports = function(root, options){
  42. options = options || {};
  43. // root required
  44. if (!root) throw new Error('static() root path required');
  45. // default redirect
  46. var redirect = false !== options.redirect;
  47. return function static(req, res, next) {
  48. if ('GET' != req.method && 'HEAD' != req.method) return next();
  49. var path = parse(req).pathname;
  50. var pause = utils.pause(req);
  51. function resume() {
  52. next();
  53. pause.resume();
  54. }
  55. function directory() {
  56. if (!redirect) return resume();
  57. var pathname = url.parse(req.originalUrl).pathname;
  58. res.statusCode = 301;
  59. res.setHeader('Location', pathname + '/');
  60. res.end('Redirecting to ' + utils.escape(pathname) + '/');
  61. }
  62. function error(err) {
  63. if (404 == err.status) return resume();
  64. next(err);
  65. }
  66. send(req, path)
  67. .maxage(options.maxAge || 0)
  68. .root(root)
  69. .index(options.index || 'index.html')
  70. .hidden(options.hidden)
  71. .on('error', error)
  72. .on('directory', directory)
  73. .pipe(res);
  74. };
  75. };
  76. /**
  77. * Expose mime module.
  78. *
  79. * If you wish to extend the mime table use this
  80. * reference to the "mime" module in the npm registry.
  81. */
  82. exports.mime = send.mime;