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