-
Notifications
You must be signed in to change notification settings - Fork 179
/
server.js
99 lines (89 loc) · 3.13 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
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
const http = require('http');
const path = require('path');
const fs = require('fs');
const fsPromises = require('fs').promises;
const logEvents = require('./logEvents');
const EventEmitter = require('events');
class Emitter extends EventEmitter { };
// initialize object
const myEmitter = new Emitter();
myEmitter.on('log', (msg, fileName) => logEvents(msg, fileName));
const PORT = process.env.PORT || 3500;
const serveFile = async (filePath, contentType, response) => {
try {
const rawData = await fsPromises.readFile(
filePath,
!contentType.includes('image') ? 'utf8' : ''
);
const data = contentType === 'application/json'
? JSON.parse(rawData) : rawData;
response.writeHead(
filePath.includes('404.html') ? 404 : 200,
{ 'Content-Type': contentType }
);
response.end(
contentType === 'application/json' ? JSON.stringify(data) : data
);
} catch (err) {
console.log(err);
myEmitter.emit('log', `${err.name}: ${err.message}`, 'errLog.txt');
response.statusCode = 500;
response.end();
}
}
const server = http.createServer((req, res) => {
console.log(req.url, req.method);
myEmitter.emit('log', `${req.url}\t${req.method}`, 'reqLog.txt');
const extension = path.extname(req.url);
let contentType;
switch (extension) {
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
case '.jpg':
contentType = 'image/jpeg';
break;
case '.png':
contentType = 'image/png';
break;
case '.txt':
contentType = 'text/plain';
break;
default:
contentType = 'text/html';
}
let filePath =
contentType === 'text/html' && req.url === '/'
? path.join(__dirname, 'views', 'index.html')
: contentType === 'text/html' && req.url.slice(-1) === '/'
? path.join(__dirname, 'views', req.url, 'index.html')
: contentType === 'text/html'
? path.join(__dirname, 'views', req.url)
: path.join(__dirname, req.url);
// makes .html extension not required in the browser
if (!extension && req.url.slice(-1) !== '/') filePath += '.html';
const fileExists = fs.existsSync(filePath);
if (fileExists) {
serveFile(filePath, contentType, res);
} else {
switch (path.parse(filePath).base) {
case 'old-page.html':
res.writeHead(301, { 'Location': '/new-page.html' });
res.end();
break;
case 'www-page.html':
res.writeHead(301, { 'Location': '/' });
res.end();
break;
default:
serveFile(path.join(__dirname, 'views', '404.html'), 'text/html', res);
}
}
});
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));