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.

80 lines
1.7 KiB

  1. /*!
  2. * Connect - favicon
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var fs = require('fs')
  11. , utils = require('../utils');
  12. /**
  13. * Favicon:
  14. *
  15. * By default serves the connect favicon, or the favicon
  16. * located by the given `path`.
  17. *
  18. * Options:
  19. *
  20. * - `maxAge` cache-control max-age directive, defaulting to 1 day
  21. *
  22. * Examples:
  23. *
  24. * Serve default favicon:
  25. *
  26. * connect()
  27. * .use(connect.favicon())
  28. *
  29. * Serve favicon before logging for brevity:
  30. *
  31. * connect()
  32. * .use(connect.favicon())
  33. * .use(connect.logger('dev'))
  34. *
  35. * Serve custom favicon:
  36. *
  37. * connect()
  38. * .use(connect.favicon('public/favicon.ico'))
  39. *
  40. * @param {String} path
  41. * @param {Object} options
  42. * @return {Function}
  43. * @api public
  44. */
  45. module.exports = function favicon(path, options){
  46. var options = options || {}
  47. , path = path || __dirname + '/../public/favicon.ico'
  48. , maxAge = options.maxAge || 86400000
  49. , icon; // favicon cache
  50. return function favicon(req, res, next){
  51. if ('/favicon.ico' == req.url) {
  52. if (icon) {
  53. res.writeHead(200, icon.headers);
  54. res.end(icon.body);
  55. } else {
  56. fs.readFile(path, function(err, buf){
  57. if (err) return next(err);
  58. icon = {
  59. headers: {
  60. 'Content-Type': 'image/x-icon'
  61. , 'Content-Length': buf.length
  62. , 'ETag': '"' + utils.md5(buf) + '"'
  63. , 'Cache-Control': 'public, max-age=' + (maxAge / 1000)
  64. },
  65. body: buf
  66. };
  67. res.writeHead(200, icon.headers);
  68. res.end(icon.body);
  69. });
  70. }
  71. } else {
  72. next();
  73. }
  74. };
  75. };