forked from garann/node-for-frontend-devs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-03.js
46 lines (42 loc) · 1.08 KB
/
02-03.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
var http = require("http"),
path = require("path"),
fs = require("fs"),
extensions = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".png": "image/png",
".gif": "image/gif",
".jpg": "image/jpeg"
};
http.createServer(function(req, res) {
var filename = path.basename(req.url) || "index.html",
ext = path.extname(filename),
dir = path.dirname(req.url).substring(1),
localPath = __dirname + "/public/";
if (extensions[ext]) {
localPath += (dir ? dir + "/" : "") + filename;
path.exists(localPath, function(exists) {
if (exists) {
getFile(localPath, extensions[ext], res);
} else {
res.writeHead(404);
res.end();
}
});
}
}).listen(8000);
function getFile(localPath, mimeType, res) {
fs.readFile(localPath, function(err, contents) {
if (!err) {
res.writeHead(200, {
"Content-Type": mimeType,
"Content-Length": contents.length
});
res.end(contents);
} else {
res.writeHead(500);
res.end();
}
});
}