43 lines
1.2 KiB
JavaScript
43 lines
1.2 KiB
JavaScript
import http from 'http';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
|
|
const port = process.env.PORT ? Number(process.env.PORT) : 5174;
|
|
const staticDir = path.resolve(process.cwd(), './static');
|
|
|
|
const mime = {
|
|
'.html': 'text/html',
|
|
'.js': 'application/javascript',
|
|
'.css': 'text/css',
|
|
'.json': 'application/json',
|
|
'.png': 'image/png',
|
|
};
|
|
|
|
const server = http.createServer((req, res) => {
|
|
try {
|
|
const reqPath = req.url === '/' ? '/sender.html' : req.url;
|
|
const filePath = path.join(staticDir, decodeURIComponent(reqPath));
|
|
if (!filePath.startsWith(staticDir)) {
|
|
res.writeHead(403); res.end('Forbidden'); return;
|
|
}
|
|
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
const ext = path.extname(filePath);
|
|
res.writeHead(200, { 'Content-Type': mime[ext] || 'text/plain' });
|
|
fs.createReadStream(filePath).pipe(res);
|
|
} else {
|
|
res.writeHead(404); res.end('Not found');
|
|
}
|
|
} catch (e) {
|
|
res.writeHead(500); res.end('Server error');
|
|
}
|
|
});
|
|
|
|
server.listen(port, () => {
|
|
console.log(`Static server running on http://localhost:${port}`);
|
|
});
|
|
|
|
// Graceful shutdown
|
|
process.on('SIGINT', () => server.close(() => process.exit(0)));
|
|
process.on('SIGTERM', () => server.close(() => process.exit(0)));
|
|
|