53 lines
1.3 KiB
JavaScript
53 lines
1.3 KiB
JavaScript
const http = require('http');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const PORT = 8080;
|
|
const PUBLIC_DIR = path.join(__dirname, 'public');
|
|
|
|
const MIME_TYPES = {
|
|
'.html': 'text/html',
|
|
'.css': 'text/css',
|
|
'.js': 'text/javascript',
|
|
'.json': 'application/json',
|
|
'.png': 'image/png',
|
|
'.jpg': 'image/jpeg',
|
|
'.svg': 'image/svg+xml',
|
|
};
|
|
|
|
const server = http.createServer((req, res) => {
|
|
let filePath = path.join(PUBLIC_DIR, req.url === '/' ? 'index.html' : req.url);
|
|
|
|
// Prevent directory traversal
|
|
if (!filePath.startsWith(PUBLIC_DIR)) {
|
|
res.statusCode = 403;
|
|
res.end('Forbidden');
|
|
return;
|
|
}
|
|
|
|
const ext = path.extname(filePath);
|
|
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
|
|
|
|
fs.readFile(filePath, (err, data) => {
|
|
if (err) {
|
|
if (err.code === 'ENOENT') {
|
|
res.statusCode = 404;
|
|
res.setHeader('Content-Type', 'text/plain');
|
|
res.end('Not Found');
|
|
} else {
|
|
res.statusCode = 500;
|
|
res.setHeader('Content-Type', 'text/plain');
|
|
res.end('Internal Server Error');
|
|
}
|
|
return;
|
|
}
|
|
res.statusCode = 200;
|
|
res.setHeader('Content-Type', contentType);
|
|
res.end(data);
|
|
});
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`Server running at http://localhost:${PORT}/`);
|
|
});
|