xonecas.io
142
St

startsInvasion / files

startsInvasion / libs / node_modules / reqwest / build / 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  // join from optional root dir
135  path = join(options.root, path);
136
137  // index.html support
138  if ('/' == path[path.length - 1]) path += 'index.html';
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    // we have a Range request
161    if (ranges) {
162      ranges = utils.parseRange(stat.size, ranges);
163      // valid
164      if (ranges) {
165        // TODO: stream options
166        // TODO: multiple support
167        var stream = fs.createReadStream(path, ranges[0])
168          , start = ranges[0].start
169          , end = ranges[0].end;
170        res.statusCode = 206;
171        res.setHeader('Content-Range', 'bytes '
172          + start
173          + '-'
174          + end
175          + '/'
176          + stat.size);
177      // invalid
178      } else {
179        return fn
180          ? fn(new Error('Requested Range Not Satisfiable'))
181          : invalidRange(res);
182      }
183    // stream the entire file
184    } else {
185      res.setHeader('Content-Length', stat.size);
186      res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000));
187      res.setHeader('Last-Modified', stat.mtime.toUTCString());
188      res.setHeader('ETag', utils.etag(stat));
189
190      // conditional GET support
191      if (utils.conditionalGET(req)) {
192        if (!utils.modified(req, res)) {
193          return utils.notModified(res);
194        }
195      }
196
197      // read stream
198      var stream = fs.createReadStream(path);
199    }
200
201    // transfer
202    if (!res.getHeader('content-type')) {
203      var charset = mime.charsets.lookup(type);
204      res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
205    }
206    res.setHeader('Accept-Ranges', 'bytes');
207
208    if (head) return res.end();
209    stream.pipe(res);
210    if (fn) {
211      res.connection.on('error', fn);
212      stream.on('end', fn);
213    }
214  });
215};