-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathindex.js
100 lines (85 loc) · 2.57 KB
/
index.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
var createServer = require("http").createServer,
readFile = require("fs").readFile,
sys = require("sys"),
url = require("url"),
mime = require("./mime");
var router = exports;
var NOT_FOUND = "Not Found\n";
function notFound(req, res) {
res.writeHead(404, [
["Content-Type", "text/plain"],
["Content-Length", NOT_FOUND.length]
]);
res.write(NOT_FOUND);
res.end();
}
router.createServer = function() {
var getMap = {};
server = createServer(function(req, res) {
if (req.method === "GET" || req.method === "HEAD") {
var handler = getMap[url.parse(req.url).pathname] || notFound;
res.simpleText = function (code, body) {
res.writeHead(code, [ ["Content-Type", "text/plain"]
, ["Content-Length", body.length]
]);
res.write(body);
res.end();
};
res.simpleJSON = function (code, obj) {
var body = JSON.stringify(obj);
var m = encodeURIComponent(body).match(/%[89ABab]/g);
res.writeHead(code, [ ["Content-Type", "text/json"]
, ["Content-Length", (body.length + (m ? m.length : 0))]
]);
res.write(body);
res.end();
};
handler(req, res);
}
});
return {
listen: function(port, host) {
server.listen(port, host);
sys.puts("Server at http://" + (host || "127.0.0.1") + ":" + port.toString() + "/");
},
get: function(path, handler) {
getMap[path] = handler;
}
};
};
function extname (path) {
var index = path.lastIndexOf(".");
return index < 0 ? "" : path.substring(index);
}
router.staticHandler = function (filename) {
var body, headers;
var content_type = mime.lookupExtension(extname(filename));
var encoding = (content_type.slice(0,4) === "text" ? "utf8" : "binary");
function loadResponseData(callback) {
if (body && headers) {
callback();
return;
}
sys.puts("loading " + filename + "...");
readFile(filename, encoding, function (err, data) {
if (err) {
sys.puts("Error loading " + filename);
} else {
body = data;
headers = [ [ "Content-Type" , content_type ]
, [ "Content-Length" , body.length ]
];
headers.push(["Cache-Control", "public"]);
sys.puts("static file " + filename + " loaded");
callback();
}
});
}
return function (req, res) {
loadResponseData(function () {
res.writeHead(200, headers);
res.write(body, encoding);
res.end();
});
};
};