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