forked from Real-Dev-Squad/website-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
65 lines (60 loc) · 1.72 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 8000;
const isAbsolutePath = require('path-is-absolute');
http
.createServer(function (req, res) {
/**
* @param {string} urlPath - the path to the requested file
* @sanitizer path.normalize
*/
const [url, params] = path.normalize(req.url).split('?');
/**
* @param {string} filePath - the absolute path to the requested file
* @flowsource urlPath
* @sanitizer path.join
* @sanitizer isAbsolutePath
*/
let filePath = path.join(__dirname, url);
if (!isAbsolutePath(filePath)) {
res.statusCode = 400;
res.end('Invalid file path');
return;
}
if (!path.extname(filePath)) {
filePath = path.join(filePath, 'index.html');
}
// Check that the file exists before reading it
if (!fs.existsSync(filePath)) {
res.statusCode = 404;
res.end('File not found');
return;
}
fs.readFile(filePath, function (err, data) {
let contentType = 'text/html';
switch (path.extname(filePath)) {
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
}
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
});
})
.listen(port, () => console.log(`Listening on port ${port}`));