-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (53 loc) · 1.79 KB
/
server.js
File metadata and controls
62 lines (53 loc) · 1.79 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
/**
* Simple local development server with correct MIME types
* Run with: node server.js
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 8000;
const PUBLIC_DIR = path.join(__dirname, 'src');
const MIME_TYPES = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.ics': 'text/calendar',
'.ical': 'text/calendar'
};
const server = http.createServer((req, res) => {
// Parse URL to handle query parameters
const url = new URL(req.url, `http://${req.headers.host}`);
let requestPath = url.pathname;
// Default to index.html for root path
if (requestPath === '/') {
requestPath = '/index.html';
}
let filePath = path.join(PUBLIC_DIR, requestPath);
const extname = path.extname(filePath);
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/html' });
res.end('<h1>404 - File Not Found</h1>', 'utf-8');
} else {
res.writeHead(500);
res.end(`Server Error: ${error.code}`, 'utf-8');
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(PORT, () => {
console.log(`🚀 Server running at http://localhost:${PORT}/`);
console.log(`📁 Serving files from: ${PUBLIC_DIR}`);
console.log(`\n💡 Press Ctrl+C to stop the server\n`);
});