xonecas.io
191
Pp

particle-play / files

particle-play / node_modules / connect / lib / middleware / directory.js

5.2 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 *  - `filter` Apply this filter function to files. Defaults to false.
39 *
40 * @param {String} root
41 * @param {Object} options
42 * @return {Function}
43 * @api public
44 */
45
46exports = module.exports = function directory(root, options){
47  options = options || {};
48
49  // root required
50  if (!root) throw new Error('directory() root path required');
51  var hidden = options.hidden
52    , icons = options.icons
53    , filter = options.filter
54    , root = normalize(root);
55
56  return function directory(req, res, next) {
57    var accept = req.headers.accept || 'text/plain'
58      , url = parse(req.url)
59      , dir = decodeURIComponent(url.pathname)
60      , path = normalize(join(root, dir))
61      , originalUrl = parse(req.originalUrl)
62      , originalDir = decodeURIComponent(originalUrl.pathname)
63      , showUp = path != root && path != root + '/';
64
65    // null byte(s)
66    if (~path.indexOf('\0')) return utils.badRequest(res);
67
68    // malicious path
69    if (0 != path.indexOf(root)) return utils.forbidden(res);
70
71    // check if we have a directory
72    fs.stat(path, function(err, stat){
73      if (err) return 'ENOENT' == err.code
74        ? next()
75        : next(err);
76
77      if (!stat.isDirectory()) return next();
78
79      // fetch files
80      fs.readdir(path, function(err, files){
81        if (err) return next(err);
82        if (!hidden) files = removeHidden(files);
83        if (filter) files = files.filter(filter);
84        files.sort();
85        // content-negotiation
86        for (var key in exports) {
87          if (~accept.indexOf(key) || ~accept.indexOf('*/*')) {
88            exports[key](req, res, files, next, originalDir, showUp, icons);
89            return;
90          }
91        }
92        utils.notAcceptable(res);
93      });
94    });
95  };
96};
97
98/**
99 * Respond with text/html.
100 */
101
102exports.html = function(req, res, files, next, dir, showUp, icons){
103  fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){
104    if (err) return next(err);
105    fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){
106      if (err) return next(err);
107      if (showUp) files.unshift('..');
108      str = str
109        .replace('{style}', style)
110        .replace('{files}', html(files, dir, icons))
111        .replace('{directory}', dir)
112		.replace('{linked-path}', htmlPath(dir));
113      res.setHeader('Content-Type', 'text/html');
114      res.setHeader('Content-Length', str.length);
115      res.end(str);
116    });
117  });
118};
119
120/**
121 * Respond with application/json.
122 */
123
124exports.json = function(req, res, files){
125  files = JSON.stringify(files);
126  res.setHeader('Content-Type', 'application/json');
127  res.setHeader('Content-Length', files.length);
128  res.end(files);
129};
130
131/**
132 * Respond with text/plain.
133 */
134
135exports.plain = function(req, res, files){
136  files = files.join('\n') + '\n';
137  res.setHeader('Content-Type', 'text/plain');
138  res.setHeader('Content-Length', files.length);
139  res.end(files);
140};
141
142/**
143 * Map html `dir`, returning a linked path.
144 */
145
146function htmlPath(dir) {
147  var curr = [];
148  return dir.split('/').map(function(part){
149    curr.push(part);
150    return '<a href="' + curr.join('/') + '">' + part + '</a>';
151  }).join(' / ');
152}
153
154/**
155 * Map html `files`, returning an html unordered list.
156 */
157
158function html(files, dir, useIcons) {
159  return '<ul id="files">' + files.map(function(file){
160    var icon = ''
161      , classes = [];
162
163    if (useIcons && '..' != file) {
164      icon = icons[extname(file)] || icons.default;
165      icon = '<img src="data:image/png;base64,' + load(icon) + '" />';
166      classes.push('icon');
167    }
168
169    return '<li><a href="'
170      + join(dir, file)
171      + '" class="'
172      + classes.join(' ') + '"'
173      + ' title="' + file + '">'
174      + icon + file + '</a></li>';
175
176  }).join('\n') + '</ul>';
177}
178
179/**
180 * Load and cache the given `icon`.
181 *
182 * @param {String} icon
183 * @return {String}
184 * @api private
185 */
186
187function load(icon) {
188  if (cache[icon]) return cache[icon];
189  return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64');
190}
191
192/**
193 * Filter "hidden" `files`, aka files
194 * beginning with a `.`.
195 *
196 * @param {Array} files
197 * @return {Array}
198 * @api private
199 */
200
201function removeHidden(files) {
202  return files.filter(function(file){
203    return '.' != file[0];
204  });
205}
206
207/**
208 * Icon map.
209 */
210
211var icons = {
212    '.js': 'page_white_code_red.png'
213  , '.c': 'page_white_c.png'
214  , '.h': 'page_white_h.png'
215  , '.cc': 'page_white_cplusplus.png'
216  , '.php': 'page_white_php.png'
217  , '.rb': 'page_white_ruby.png'
218  , '.cpp': 'page_white_cplusplus.png'
219  , '.swf': 'page_white_flash.png'
220  , '.pdf': 'page_white_acrobat.png'
221  , 'default': 'page_white.png'
222};