xonecas.io
142
St

startsInvasion / files

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

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