-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
65 lines (57 loc) · 1.6 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
import * as http from 'http';
import * as fs from 'fs';
import * as path from 'path';
const PORT = process.env.PORT || 8000;
const PUBLIC_DIR = '.';
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
};
const server = http.createServer((req, res) => {
// Remove query strings and decode URI
const filePath = path.join(
PUBLIC_DIR,
decodeURIComponent(req.url.split('?')[0] === '/'
? 'index.html'
: req.url.split('?')[0])
);
const extname = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[extname] || 'application/octet-stream';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
// File not found
res.writeHead(404);
res.end('404 Not Found');
} else {
// Server error
res.writeHead(500);
res.end(`Server Error: ${err.code}`);
}
} else {
// Success
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
}
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
process.on('SIGTERM', () => {
server.close(() => {
process.exit(0);
});
});
process.on('SIGINT', () => {
server.close(() => {
process.exit(0);
});
});