/
http-file-server.js
executable file
·302 lines (261 loc) · 9.98 KB
/
http-file-server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env node
/*!
* Node.JS HTTP file server
*
* Author: Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* License: GPLv3
*/
// default configs
var host = 'localhost';
var port = 8080;
var filesPath = null;
var browse = false;
var debug = false;
var noCache = false;
var defEnc = 'utf-8';
var contentTypes = {
// case insensitive
/** pages/styles/plain-text */
'.html' : 'text/html; charset='+defEnc,
'.css' : 'text/css; charset='+defEnc,
'.less' : 'text/css; charset='+defEnc, // see ‘less’ css framework
'.js' : 'text/javascript; charset='+defEnc,
'.txt' : 'text/plain; charset='+defEnc,
/** images */
'.png' : 'image/png',
'.jpeg' : 'image/jpeg',
'.jpg' : 'image/jpeg',
'.jpe' : 'image/jpeg',
'.gif' : 'image/gif',
'.svg' : 'image/svg+xml; charset='+defEnc,
'.svgz' : 'image/svg+xml; charset='+defEnc,
'.ico' : 'image/x-icon',
/** fonts */
'.eot' : 'application/vnd.ms-fontobject',
'.woff' : 'application/font-woff',
'.ttf' : 'font/ttf',
/** downloading other files */
'*' : 'application/octet-stream'
};
var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');
var spawn = require('child_process').spawn;
for (var i=2, arg=process.argv[i]; i<process.argv.length; i++, arg=process.argv[i]) {
if (/^--help$/.test(arg)) {
console.log(
'\nUSAGE\n=====\n\n'
+'--help View this information\n'
+'--path=abc Set path of file server root directory (default is current dir)\n'
+'--host=abc Hostname of http-server (default is "'+host+'"), use "*" for any host\n'
+'--port=abc Port of http-server (default is "'+port+'")\n'
+'--browse Open hostname in browser (via "xdg-open")\n'
+'--debug Logging every request\n'
+'--no-cache Disable caching in headers\n'
);
process.exit(0);
} else if (/^--path=.+$/.test(arg)) {
if (filesPath === null) filesPath = arg.replace(/^--path=/, '');
} else if (/^--host=.+$/.test(arg)) {
host = arg.replace(/^--host=/, '');
if (host == '*') host = null;
} else if (/^--port=.+$/.test(arg)) {
port = arg.replace(/^--port=/, '');
} else if (/^--browse$/.test(arg)) {
browse = true;
} else if (/^--debug$/.test(arg)) {
debug = true;
} else if (/^--no-cache$/.test(arg)) {
noCache = true;
} else {
console.error('Unknown argument "'+arg+'"');
console.log('Run with --help argument for view usage information');
process.exit(1);
}
}
if (filesPath === null) {
filesPath = process.cwd();
console.warn('Path is empty! Will be used current work dir: "'+filesPath+'"');
console.warn('For specific path, start this app with: --path=/specific/path');
}
filesPath = filesPath
.replace('~', process.env['HOME'])
.replace(/^\.\//, process.cwd()+'/');
http.createServer(function (req, res) {
var msgHTTP200 = ' (HTTP status: 200)';
var msgHTTP404 = ' (HTTP status: 404)';
var msgHTTP500 = ' (HTTP status: 500)';
var pathname = url.parse(req.url).pathname;
pathname = decodeURIComponent(pathname.split('+').join(' '));
while (pathname.substr(0, 1) == '/') {
pathname = pathname.substr(1);
}
debug && console.log('HTTP-request for pathname: "/'+pathname+'"');
var fullPath = path.join(filesPath, pathname);
var fileDescriptor = null;
var fileStat = null;
function tellAboutError(errNum, errMsg) {
res.writeHead(errNum, {'Content-Type': 'text/plain; charset=utf-8'});
res.end('Error '+errNum+'. '+errMsg);
}
function listDir() {
var template = '<!doctype html>'
+'<html>'
+'<head>'
+'<meta charset="utf-8">'
+'<title>Directory "#PATHNAME#"</title>'
+'</head>'
+'<body>'
+'<h1>Directory "#PATHNAME#"</h1>'
+'<ul>'
+'#LIST_ELEMENTS#'
+'</ul>'
+'</body>'
+'</html>';
var listElementTemplate = '<li>#TYPE# <a href="#LINK#">#TITLE#</a></li>';
debug && console.log('Listing directory "'+fullPath+'" ...');
fs.readdir(fullPath, function (err, files) {
if (err) {
debug && console.error('Read dir error "'+fullPath+'"'+msgHTTP500);
tellAboutError(500, 'Cannot read directory.');
return;
}
var dirsList = [];
var filesList = [];
var listElements = '';
if (pathname !== '' && pathname !== '/') {
listElements += listElementTemplate
.replace(/#TYPE#/g, '[D]')
.replace(/#LINK#/g, './..')
.replace(/#TITLE#/g, '..');
}
files.forEach(function (file) {
var filePath = path.join(fullPath, file);
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
dirsList.push(file);
} else if (stat.isFile()) {
filesList.push(file);
}
});
dirsList = dirsList.sort();
filesList = filesList.sort();
dirsList.forEach(function (name) {
listElements += listElementTemplate
.replace(/#TYPE#/g, '[D]')
.replace(/#LINK#/g, './'+name+'/')
.replace(/#TITLE#/g, name);
});
filesList.forEach(function (name) {
listElements += listElementTemplate
.replace(/#TYPE#/g, '[F]')
.replace(/#LINK#/g, './'+name)
.replace(/#TITLE#/g, name);
});
var html = template
.replace(/#PATHNAME#/g, '/' + pathname)
.replace(/#LIST_ELEMENTS#/g, listElements);
var head = {};
head['Content-Type'] = 'text/html; charset=utf-8';
head['Content-Length'] = Buffer.byteLength(html, defEnc);
if (noCache) {
head['Cache-Control'] = 'no-cache, no-store, must-revalidate';
head['Pragma'] = 'no-cache';
head['Expires'] = '0';
}
debug && console.log('Directory "'+fullPath+'" is opened'+msgHTTP200);
res.writeHead(200, head);
res.end(html);
});
}
function openFile() {
debug && console.log('Opening file "'+fullPath+'" ...');
var stream = fs.createReadStream(fullPath, 'binary', {
flags: 'r',
encoding: defEnc,
autoClose: true
});
var head = {};
head['Content-Length'] = fileStat.size;
if (noCache) {
head['Cache-Control'] = 'no-cache, no-store, must-revalidate';
head['Pragma'] = 'no-cache';
head['Expires'] = '0';
}
for (var ext in contentTypes) {
if (ext == '*') continue;
if (ext == path.extname(fullPath)) {
debug && console.log('File "'+fullPath+'" mime-type is "'
+contentTypes[ext]+'"'+msgHTTP200);
head['Content-Type'] = contentTypes[ext];
}
}
if ( ! ('Content-Type' in head)) {
if (typeof contentTypes['*'] === 'string') {
debug && console.log('File "'+fullPath+'" mime-type is "'
+contentTypes['*']+'"'+msgHTTP200);
head['Content-Type'] = contentTypes['*'];
} else {
debug && console.log('Cannot detect file mime-type "'
+fullPath+'"'+msgHTTP200);
}
}
res.writeHead(200, head);
debug && console.log('Reading file "'+fullPath+'" ...');
stream.on('data', function (chunk) {
res.write(chunk, 'binary');
});
stream.on('error', function (err) {
debug && console.error('Read file error "'+fullPath+'"'+msgHTTP500);
tellAboutError(500, 'Cannot read file.');
});
stream.on('end', function () {
debug && console.log('Reading file "'+fullPath+'" is finished');
res.end();
});
}
function getStatCallback(err, stat) {
if (err) {
debug && console.error('Cannot get file stat "'+fullPath+'"'+msgHTTP500);
tellAboutError(500, 'Cannot open this path.');
return;
}
fileStat = stat;
if (fileStat.isFile()) {
process.nextTick(openFile);
} else if (fileStat.isDirectory()) {
process.nextTick(listDir);
} else {
debug && console.error('Unknown type of inode "'+fullPath+'"'+msgHTTP500);
tellAboutError(500, 'Cannot open this path.');
return;
}
}
fs.exists(fullPath, function (exists) {
if ( ! exists) {
debug && console.error('Path "'+fullPath+'" is not found'+msgHTTP404);
tellAboutError(404, 'Page not found.');
return;
}
/** opening file descriptor */
fs.open(fullPath, 'r', function (err, fd) {
if (err) {
debug && console.error('Cannot open file descriptor "'+fullPath+'"'+msgHTTP500);
tellAboutError(500, 'Cannot open this path.');
return;
}
fileDescriptor = fd;
fs.fstat(fileDescriptor, getStatCallback);
});
});
}).listen(port, host, function () {
var httpAddr = 'http://'+((host) ? host : 'localhost')+':'+port;
var host = (host) ? host : '*';
console.log('HTTP-server started at '+host+':'+port+', files path is: "'+filesPath+'"');
if (browse) {
console.log('Start xdg-open to open page "'+httpAddr+'" in browser');
spawn('xdg-open', [httpAddr], { stdio: 'inherit' });
}
});
// vim: set fenc=utf-8 ts=4 sw=4 expandtab :