This repository has been archived by the owner on Dec 2, 2020. It is now read-only.
/
endpoint.js
86 lines (75 loc) · 2.2 KB
/
endpoint.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
var fs = require("fs"),
url = require("url"),
path = require("path"),
cube = require("../");
exports.re = re;
exports.exact = exact;
exports.file = file;
var types = {
html: "text/html;charset=utf-8",
css: "text/css;charset=utf-8",
js: "text/javascript;charset=utf-8",
json: "application/json;charset=utf-8",
png: "image/png"
};
function exact(method, path, dispatch) {
return {
match: arguments.length < 3
? (dispatch = path, path = method, function(p) { return p == path; })
: function(p, m) { return m == method && p == path; },
dispatch: dispatch
};
}
function re(re, dispatch) {
return {
match: function(p) { return re.test(p); },
dispatch: dispatch
};
}
function file() {
var files = Array.prototype.slice.call(arguments),
type = types[files[0].substring(files[0].lastIndexOf(".") + 1)];
return function(request, response) {
var modified = -Infinity,
size = 0,
n = files.length;
files.forEach(function(file) {
fs.stat(file, function(error, stats) {
if (error) throw fiveohoh(request, response), error;
size += stats.size;
var time = new Date(stats.mtime);
if (time > modified) modified = time;
if (!--n) respond();
});
});
function respond() {
var status = modified <= new Date(request.headers["if-modified-since"]) ? 304 : 200,
hasBody = status === 200 && request.method !== "HEAD";
var headers = {
"Content-Type": type,
"Date": new Date().toUTCString(),
"Last-Modified": modified.toUTCString()
};
if (hasBody) {
headers["Content-Length"] = size;
response.writeHead(status, headers);
read(0);
} else {
response.writeHead(status, headers);
response.end();
}
}
function read(i) {
fs.readFile(files[i], function(error, data) {
if (error) throw fiveohoh(request, response), error;
response.write(data);
if (i < files.length - 1) read(i + 1);
else response.end();
});
}
};
};
function fiveohoh(request, response) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.end("500 Server Error");
}