-
Notifications
You must be signed in to change notification settings - Fork 0
/
StaticEndpoint.js
78 lines (72 loc) · 2.31 KB
/
StaticEndpoint.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
'use strict';
var mime = require('./mime.js'),
Endpoint = require('./Endpoint.js'),
fs = require('fs');
class StaticEndpoint extends Endpoint {
constructor (str, root) {
super("get", str, function (request, res) {
var localPath = request.path.slice(str.length); // remove the url match segment so "/public/myfile.js" can become "./www/myfile.js"
if (request.ext === "") {
// serve index
if (this.index) {
this.generateIndex(str, root, localPath, res);
} else {
StaticEndpoint.generateError(res, 404, "Indexing is disabled on this server");
}
} else {
// attempt to serve file
res.setHeader("Content-Type", mime(request.ext));
var stream = fs.createReadStream(root + localPath);
stream.on('error', function () {
StaticEndpoint.generateError(res, 404, "Cannot read requested file");
});
stream.on('open', function () {
res.statusCode = 200;
});
stream.pipe(res);
}
});
this.index = true;
// match path & root MUST finish with a "/" for correct path construction
if (/\/$/.test(root) === false) {
root += "/";
}
if (/\/$/.test(str) === false) {
str += "/";
}
}
generateIndex (virtualRoot, root, path, res) {
res.setHeader("Content-Type", mime("html"));
fs.readdir(root + path, function (err, files) {
if (err) {
StaticEndpoint.generateError(res, 404, "Cannot read requested directory");
} else {
res.statusCode = 200;
var i = 0,
l = files.length,
absolutePath,
output = [
"<!DOCTYPE html>",
"<html>",
"<head>",
"<style>",
"</style>",
"</head>",
"<body>",
"<ul>",
];
for (; i < l; i++) {
if (files[i][0] !== ".") {
absolutePath = (virtualRoot + path + "/" + files[i]).replace(/\/+/g, '/'); // remove duplicate "/"
output.push("<li><a href=\"" + absolutePath + "\">" + files[i] + "</a></li>");
}
}
output.push("</ul>")
output.push("</body>");
output.push("</html>");
res.end(output.join("\n"));
}
});
}
}
module.exports = StaticEndpoint;