xonecas.io
142
St

startsInvasion / files

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

4.5 KB
1
2/*!
3 * Connect - directory
4 * Copyright(c) 2011 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
6 * MIT Licensed
7 */
8
9// TODO: icon / style for directories
10// TODO: arrow key navigation
11// TODO: make icons extensible
12
13/**
14 * Module dependencies.
15 */
16
17var fs = require('fs')
18  , parse = require('url').parse
19  , utils = require('../utils')
20  , path = require('path')
21  , normalize = path.normalize
22  , extname = path.extname
23  , join = path.join;
24
25/**
26 * Icon cache.
27 */
28
29var cache = {};
30
31/**
32 * Serve directory listings with the given `root` path.
33 *
34 * Options:
35 *
36 *  - `hidden` display hidden (dot) files. Defaults to false
37 *  - `icons` display icons. Defaults to false
38 *
39 * @param {String} root
40 * @param {Object} options
41 * @return {Function}
42 * @api public
43 */
44
45exports = module.exports = function directory(root, options){
46  options = options || {};
47
48  // root required
49  if (!root) throw new Error('directory() root path required');
50  var hidden = options.hidden
51    , icons = options.icons
52    , root = normalize(root);
53
54  return function directory(req, res, next) {
55    var accept = req.headers.accept || 'text/plain'
56      , url = parse(req.url)
57      , dir = decodeURIComponent(url.pathname)
58      , path = normalize(join(root, dir))
59      , showUp = path != root && path != root + '/';
60
61    // malicious path
62    if (0 != path.indexOf(root)) return utils.forbidden(res);
63
64    // check if we have a directory
65    fs.stat(path, function(err, stat){
66      if (err) return 'ENOENT' == err.code
67        ? next()
68        : next(err);
69
70      if (!stat.isDirectory()) return next();
71
72      // fetch files
73      fs.readdir(path, function(err, files){
74        if (err) return next(err);
75        if (!hidden) files = removeHidden(files);
76        // content-negotiation
77        for (var key in exports) {
78          if (~accept.indexOf(key) || ~accept.indexOf('*/*')) {
79            exports[key](req, res, files, next, dir, showUp, icons);
80            return;
81          }
82        }
83        utils.notAcceptable(res);
84      });
85    });
86  };
87};
88
89/**
90 * Respond with text/html.
91 */
92
93exports.html = function(req, res, files, next, dir, showUp, icons){
94  fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){
95    if (err) return next(err);
96    fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){
97      if (err) return next(err);
98      if (showUp) files.unshift('..');
99      str = str
100        .replace('{style}', style)
101        .replace('{files}', html(files, dir, icons))
102        .replace(/\{directory\}/g, dir);
103      res.setHeader('Content-Type', 'text/html');
104      res.setHeader('Content-Length', str.length);
105      res.end(str);
106    });
107  });
108};
109
110/**
111 * Respond with application/json.
112 */
113
114exports.json = function(req, res, files){
115  files = JSON.stringify(files);
116  res.setHeader('Content-Type', 'application/json');
117  res.setHeader('Content-Length', files.length);
118  res.end(files);
119};
120
121/**
122 * Respond with text/plain.
123 */
124
125exports.plain = function(req, res, files){
126  files = files.join('\n') + '\n';
127  res.setHeader('Content-Type', 'text/plain');
128  res.setHeader('Content-Length', files.length);
129  res.end(files);
130};
131
132/**
133 * Map html `files`, returning an html unordered list.
134 */
135
136function html(files, dir, useIcons) {
137  return '<ul id="files">' + files.map(function(file){
138    var icon = ''
139      , classes = [];
140
141    if (useIcons && '..' != file) {
142      icon = icons[extname(file)] || icons.default;
143      icon = '<img src="data:image/png;base64,' + load(icon) + '" />';
144      classes.push('icon');
145    }
146
147    return '<li><a href="'
148      + join(dir, file)
149      + '" class="'
150      + classes.join(' ') + '"'
151      + ' title="' + file + '">'
152      + icon + file + '</a></li>';
153
154  }).join('\n') + '</ul>';
155}
156
157/**
158 * Load and cache the given `icon`.
159 *
160 * @param {String} icon
161 * @return {String}
162 * @api private
163 */
164
165function load(icon) {
166  if (cache[icon]) return cache[icon];
167  return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64');
168}
169
170/**
171 * Filter "hidden" `files`, aka files
172 * beginning with a `.`.
173 *
174 * @param {Array} files
175 * @return {Array}
176 * @api private
177 */
178
179function removeHidden(files) {
180  return files.filter(function(file){
181    return '.' != file[0];
182  });
183}
184
185/**
186 * Icon map.
187 */
188
189var icons = {
190    '.js': 'page_white_code_red.png'
191  , '.c': 'page_white_c.png'
192  , '.h': 'page_white_h.png'
193  , '.cc': 'page_white_cplusplus.png'
194  , '.php': 'page_white_php.png'
195  , '.rb': 'page_white_ruby.png'
196  , '.cpp': 'page_white_cplusplus.png'
197  , '.swf': 'page_white_flash.png'
198  , '.pdf': 'page_white_acrobat.png'
199  , 'default': 'page_white.png'
200};