-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
57 lines (47 loc) · 1.57 KB
/
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
const config = require("./config");
const http = require("http");
const fs = require("fs");
const path = require("path");
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((request, response) => {
function notFound() {
response.writeHead(404);
response.end('Resource not found.\n');
response.end();
}
function getMimeType(ext) {
var mime = config.defaultMimeType;
for (type in config.mimeTypes)
if (config.mimeTypes[type].indexOf(ext) != -1)
mime = type;
return mime;
}
var virtualPath = request.url;
if (virtualPath == "/" && config.defaultDocument)
virtualPath = "/" + config.defaultDocument;
var filePath = config.root + virtualPath;
var contentType = getMimeType(path.extname(filePath));
if (fs.existsSync(filePath))
fs.readFile(filePath, function (error, content) {
if (error) {
if (error.code == 'ENOENT') {
notFound();
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
else
notFound();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});