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