-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
47 lines (39 loc) · 1.07 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
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
function send404(response) {
response.writeHead(404, {"Content-type" : "text/plain"});
response.write("Error 404: resource not found");
response.end();
}
function sendPage(response, filePath, fileContents) {
response.writeHead(200, {"Content-type" : mime.getType(path.basename(filePath))});
response.end(fileContents);
}
function serverWorking(response, absPath) {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response)
} else {
sendPage(response, absPath, data);
}
});
} else {
send404(response);
}
});
}
var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = "index.html";
} else {
filePath = request.url;
}
var absPath = "./" + filePath;
serverWorking(response, absPath);
});
var port_number = server.listen(process.env.PORT || 3000);