-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebserver.js
More file actions
127 lines (116 loc) · 3.9 KB
/
webserver.js
File metadata and controls
127 lines (116 loc) · 3.9 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// const http = require("http");
// const path = require("path");
// const port = 3000;
// const fs = require("fs");
// const server = http.createServer((req, res) => {
// res.statusCode = 200;
// // res.setHeader('Content-Type', 'text/html');
// // res.end('<h1>Hello World</h1>');
// res.writeHead(200, { 'Content-Type': 'text/html' });
// fs.readFile('index.html', (error,data) => {
// if (error) {
// res.writeHead(404);
// res.write("page nt found");
// return;
// } else {
// res.write(data);
// }
// res.end();
// });
// });
// server.listen(port, (error) => {
// if (error) {
// console.error("Error starting server:", error);
// return;
// }
// console.log(`Server running at http://localhost:${port}/`);
// });
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}`));