-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
60 lines (53 loc) · 1.62 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const MIME_TYPES = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm'
};
function getContentType(filePath) {
const ext = path.extname(filePath);
return MIME_TYPES[ext] || 'application/octet-stream';
}
const server = http.createServer((req, res) => {
// Handle favicon.ico requests
if (req.url === '/favicon.ico') {
res.writeHead(204);
res.end();
return;
}
// Normalize file path
let filePath = '.' + (req.url === '/' ? '/index.html' : req.url);
// Read file
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end('404 Not Found');
} else {
res.writeHead(500);
res.end('500 Internal Server Error');
}
} else {
res.writeHead(200, { 'Content-Type': getContentType(filePath) });
res.end(content, 'utf-8');
}
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});