-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·58 lines (47 loc) · 1.29 KB
/
server.js
File metadata and controls
executable file
·58 lines (47 loc) · 1.29 KB
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
const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime');
const port = process.env.PORT || 3000;
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.lookup(path.basename(filePath))});
response.end(fileContents);
}
function serverWorking(response, absolutePath) {
fs.exists(absolutePath, exists => {
if (exists) {
fs.readFile(absolutePath, (err, data) => {
if (err) {
send404(response);
} else {
sendPage(response, absolutePath, data);
}
});
} else {
send404(response);
}
});
}
const requestHandler = (request, response) => {
console.log(request.url);
let filePath;
if (request.url === '/') {
filePath = '/index.html';
} else {
filePath = '/' + request.url;
}
const absolutePath = './' + filePath;
serverWorking(response, absolutePath);
};
const server = http.createServer(requestHandler);
server.listen(port, err => {
if (err) {
return console.log('something bad happened', err);
}
console.log(`server is listening on ${port}`);
});