static.js
This file
Path
lib/middleware/static.js
87 lines · 2.1 KiB · JavaScript
Last changed by
remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
History of this fileTake it
remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
lines 1–87why, one step back1/*!2 * Connect - static3 * Copyright(c) 2010 Sencha Inc.4 * Copyright(c) 2011 TJ Holowaychuk5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var send = require('send')13 , utils = require('../utils')14 , parse = utils.parseUrl15 , url = require('url');1617/**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 035 * - `hidden` Allow transfer of hidden files. defaults to false36 * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true37 * - `index` Default file name, defaults to 'index.html'38 *39 * @param {String} root40 * @param {Object} options41 * @return {Function}42 * @api public43 */4445exports = module.exports = function(root, options){46 options = options || {};4748 // root required49 if (!root) throw new Error('static() root path required');5051 // default redirect52 var redirect = false !== options.redirect;5354 return function staticMiddleware(req, res, next) {55 if ('GET' != req.method && 'HEAD' != req.method) return next();56 var originalUrl = url.parse(req.originalUrl);57 var path = parse(req).pathname;5859 if (path == '/' && originalUrl.pathname[originalUrl.pathname.length - 1] != '/') {60 return directory();61 }6263 function directory() {64 if (!redirect) return next();65 var target;66 originalUrl.pathname += '/';67 target = url.format(originalUrl);68 res.statusCode = 303;69 res.setHeader('Location', target);70 res.end('Redirecting to ' + utils.escape(target));71 }7273 function error(err) {74 if (404 == err.status) return next();75 next(err);76 }7778 send(req, path)79 .maxage(options.maxAge || 0)80 .root(root)81 .index(options.index || 'index.html')82 .hidden(options.hidden)83 .on('error', error)84 .on('directory', directory)85 .pipe(res);86 };87};