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