xonecas.io
818
Du

dustymarkdown / files

dustymarkdown / node_modules / connect / lib / middleware / static.js

4.9 KB
1
2/*!
3 * Connect - staticProvider
4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
6 * MIT Licensed
7 */
8
9/**
10 * Module dependencies.
11 */
12
13var fs = require('fs')
14  , join = require('path').join
15  , basename = require('path').basename
16  , utils = require('../utils')
17  , Buffer = require('buffer').Buffer
18  , parse = require('url').parse
19  , mime = require('mime');
20
21/**
22 * Static file server with the given `root` path.
23 *
24 * Examples:
25 *
26 *     var oneDay = 86400000;
27 *
28 *     connect(
29 *       connect.static(__dirname + '/public')
30 *     ).listen(3000);
31 *
32 *     connect(
33 *       connect.static(__dirname + '/public', { maxAge: oneDay })
34 *     ).listen(3000);
35 *
36 * Options:
37 *
38 *    - `maxAge`   Browser cache maxAge in milliseconds. defaults to 0
39 *    - `hidden`   Allow transfer of hidden files. defaults to false
40 *
41 * @param {String} root
42 * @param {Object} options
43 * @return {Function}
44 * @api public
45 */
46
47exports = module.exports = function static(root, options){
48  options = options || {};
49
50  // root required
51  if (!root) throw new Error('static() root path required');
52  options.root = root;
53
54  return function static(req, res, next) {
55    options.path = req.url;
56    send(req, res, next, options);
57  };
58};
59
60/**
61 * Expose mime module.
62 */
63
64exports.mime = mime;
65
66/**
67 * Respond with 403 "Forbidden".
68 *
69 * @param {ServerResponse} res
70 * @api private
71 */
72
73function forbidden(res) {
74  var body = 'Forbidden';
75  res.setHeader('Content-Type', 'text/plain');
76  res.setHeader('Content-Length', body.length);
77  res.statusCode = 403;
78  res.end(body);
79}
80
81/**
82 * Respond with 416  "Requested Range Not Satisfiable"
83 *
84 * @param {ServerResponse} res
85 * @api private
86 */
87
88function invalidRange(res) {
89  var body = 'Requested Range Not Satisfiable';
90  res.setHeader('Content-Type', 'text/plain');
91  res.setHeader('Content-Length', body.length);
92  res.statusCode = 416;
93  res.end(body);
94}
95
96/**
97 * Attempt to tranfer the requseted file to `res`.
98 *
99 * @param {ServerRequest}
100 * @param {ServerResponse}
101 * @param {Function} next
102 * @param {Object} options
103 * @api private
104 */
105
106var send = exports.send = function(req, res, next, options){
107  options = options || {};
108  if (!options.path) throw new Error('path required');
109
110  // setup
111  var maxAge = options.maxAge || 0
112    , ranges = req.headers.range
113    , head = 'HEAD' == req.method
114    , root = options.root
115    , fn = options.callback
116    , hidden = options.hidden;
117
118  // replace next() with callback when available
119  if (fn) next = fn;
120
121  // ignore non-GET requests
122  if ('GET' != req.method && !head) return next();
123
124  // parse url
125  var url = parse(options.path)
126    , path = decodeURIComponent(url.pathname)
127    , type;
128
129  // potentially malicious path
130  if (~path.indexOf('..')) return fn
131    ? fn(new Error('Forbidden'))
132    : forbidden(res);
133    
134  // index.html support
135  if ('/' == path[path.length - 1]) path += 'index.html';
136
137  // join from optional root dir
138  path = join(options.root, path);
139
140  // "hidden" file
141  if (!hidden && '.' == basename(path)[0]) return next();
142
143  // mime type
144  type = mime.lookup(path);
145
146  fs.stat(path, function(err, stat){
147    // ignore ENOENT
148    if (err) {
149      if (fn) return fn(err);
150      return 'ENOENT' == err.code
151        ? next()
152        : next(err);
153    // ignore directories
154    } else if (stat.isDirectory()) {
155      return fn
156        ? fn(new Error('Cannot Transfer Directory'))
157        : next();
158    }
159
160    var opts = {};
161
162    // we have a Range request
163    if (ranges) {
164      ranges = utils.parseRange(stat.size, ranges);
165      // valid
166      if (ranges) {
167        // TODO: stream options
168        // TODO: multiple support
169        opts.start = ranges[0].start;
170        opts.end = ranges[0].end;
171        res.statusCode = 206;
172        res.setHeader('Content-Range', 'bytes '
173          + opts.start
174          + '-'
175          + opts.end
176          + '/'
177          + stat.size);
178      // invalid
179      } else {
180        return fn
181          ? fn(new Error('Requested Range Not Satisfiable'))
182          : invalidRange(res);
183      }
184    // stream the entire file
185    } else {
186      res.setHeader('Content-Length', stat.size);
187      res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000));
188      res.setHeader('Last-Modified', stat.mtime.toUTCString());
189      res.setHeader('ETag', utils.etag(stat));
190
191      // conditional GET support
192      if (utils.conditionalGET(req)) {
193        if (!utils.modified(req, res)) {
194          return utils.notModified(res);
195        }
196      }
197    }
198
199    // header fields
200    if (!res.getHeader('content-type')) {
201      var charset = mime.charsets.lookup(type);
202      res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
203    }
204    res.setHeader('Accept-Ranges', 'bytes');
205
206    // transfer
207    if (head) return res.end();
208
209    var stream = fs.createReadStream(path, opts);
210    stream.pipe(res);
211    if (fn) {
212      res.connection.on('error', fn);
213      stream.on('end', fn);
214    }
215  });
216};