-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
43 lines (38 loc) · 1.38 KB
/
server.js
File metadata and controls
43 lines (38 loc) · 1.38 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
// server.js
import http from 'http';
import fs from 'fs';
import path from 'path';
// Allow port configuration via command line argument or environment variable, default to 3000
const PORT = process.env.PORT || process.argv[2] || 3000;
// MIME types mapping required for ES6 modules
const MIME_TYPES = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.bas': 'text/plain',
'.md': 'text/markdown'
};
http.createServer((req, res) => {
// Serve index.html if the URL is the root
let filePath = '.' + req.url;
if (filePath === './') filePath = './index.html';
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = MIME_TYPES[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if(error.code === 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found');
} else {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Server error: ' + error.code);
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
}).listen(PORT, () => {
console.log(`🚀 Server running at: http://localhost:${PORT}`);
console.log(`Press Ctrl+C to quit.`);
});