socketioMEANseed/www/node_modules/union/examples/simple/middleware/favicon.js
www/node_modules/union/examples/simple/middleware/favicon.jsRaw
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
13var crypto = require('crypto')
14 , fs = require('fs');
15
16/**
17 * Favicon cache.
18 */
19
20var icon;
21
22/**
23 * Return md5 hash of the given string and optional encoding,
24 * defaulting to hex.
25 *
26 * utils.md5('wahoo');
27 * // => "e493298061761236c96b02ea6aa8a2ad"
28 *
29 * @param {String} str
30 * @param {String} encoding
31 * @return {String}
32 * @api public
33 */
34
35exports.md5 = function (str, encoding) {
36 return crypto
37 .createHash('md5')
38 .update(str)
39 .digest(encoding || 'hex');
40};
41
42/**
43 * By default serves the connect favicon, or the favicon
44 * located by the given `path`.
45 *
46 * Options:
47 *
48 * - `maxAge` cache-control max-age directive, defaulting to 1 day
49 *
50 * Examples:
51 *
52 * connect.createServer(
53 * connect.favicon()
54 * );
55 *
56 * connect.createServer(
57 * connect.favicon(__dirname + '/public/favicon.ico')
58 * );
59 *
60 * @param {String} path
61 * @param {Object} options
62 * @return {Function}
63 * @api public
64 */
65
66module.exports = function favicon(path, options) {
67 var options = options || {}
68 , path = path || __dirname + '/../public/favicon.ico'
69 , maxAge = options.maxAge || 86400000;
70
71 return function favicon(req, res, next) {
72 if ('/favicon.ico' == req.url) {
73 if (icon) {
74 res.writeHead(200, icon.headers);
75 res.end(icon.body);
76 } else {
77 fs.readFile(path, function (err, buf) {
78 if (err) return next(err);
79 icon = {
80 headers: {
81 'Content-Type': 'image/x-icon'
82 , 'Content-Length': buf.length
83 , 'ETag': '"' + exports.md5(buf) + '"'
84 , 'Cache-Control': 'public, max-age=' + (maxAge / 1000)
85 },
86 body: buf
87 };
88 res.writeHead(200, icon.headers);
89 res.end(icon.body);
90 });
91 }
92 } else {
93 next();
94 }
95 };
96};