32 lines
862 B
JavaScript
32 lines
862 B
JavaScript
const http = require('http');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
const server = http.createServer((req, res) => {
|
|
let filePath = req.url.split('?')[0];
|
|
if (filePath === '/') filePath = '/index.html';
|
|
const safePath = path.join(__dirname, filePath);
|
|
|
|
if (!safePath.startsWith(__dirname)) {
|
|
res.writeHead(403);
|
|
return res.end('Forbidden');
|
|
}
|
|
|
|
fs.readFile(safePath, (err, data) => {
|
|
if (err) {
|
|
res.writeHead(404);
|
|
return res.end('Not Found');
|
|
}
|
|
const ext = path.extname(safePath);
|
|
const contentType = ext === '.css' ? 'text/css' : ext === '.js' ? 'application/javascript' : 'text/html';
|
|
res.writeHead(200, { 'Content-Type': contentType });
|
|
res.end(data);
|
|
});
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`Server running on port ${PORT}`);
|
|
});
|