|
| 1 | +import http from 'node:http'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { fileURLToPath } from 'node:url'; |
| 5 | + |
| 6 | +const __filename = fileURLToPath(import.meta.url); |
| 7 | +const __dirname = path.dirname(__filename); |
| 8 | + |
| 9 | +const PORT = process.env.PORT || 3000; |
| 10 | +const baseDir = __dirname; |
| 11 | + |
| 12 | +// MIME types |
| 13 | +const mimeTypes = { |
| 14 | + '.html': 'text/html', |
| 15 | + '.js': 'application/javascript', |
| 16 | + '.css': 'text/css', |
| 17 | + '.json': 'application/json', |
| 18 | + '.ico': 'image/x-icon', |
| 19 | + '.png': 'image/png', |
| 20 | + '.jpg': 'image/jpeg', |
| 21 | + '.jpeg': 'image/jpeg', |
| 22 | + '.svg': 'image/svg+xml', |
| 23 | + '.txt': 'text/plain', |
| 24 | + '.wasm': 'application/wasm' |
| 25 | +}; |
| 26 | + |
| 27 | +// SSE clients |
| 28 | +const clients = []; |
| 29 | + |
| 30 | +// Load index.html once at startup for instant serving |
| 31 | +const indexPath = path.join(baseDir, 'index.html'); |
| 32 | +let indexHTML = ''; |
| 33 | +try { |
| 34 | + indexHTML = fs.readFileSync(indexPath, 'utf-8'); |
| 35 | + console.log('[startup] Loaded index.html into memory.'); |
| 36 | +} catch (err) { |
| 37 | + console.error('[startup] Could not read index.html:', err); |
| 38 | +} |
| 39 | + |
| 40 | +// SSE helpers |
| 41 | +function sendSSE(res, event, data) { |
| 42 | + res.write(`event: ${event}\n`); |
| 43 | + res.write(`data: ${JSON.stringify(data)}\n\n`); |
| 44 | +} |
| 45 | + |
| 46 | +function broadcastFileChange(filename, content) { |
| 47 | + clients.forEach(client => { |
| 48 | + sendSSE(client, 'fileUpdate', { filename, content }); |
| 49 | + }); |
| 50 | +} |
| 51 | + |
| 52 | +// Watch the root for changes to lessonFile.vue |
| 53 | +fs.watch(baseDir, { recursive: false }, (eventType, filename) => { |
| 54 | + if (filename === 'lessonFile.vue') { |
| 55 | + const filePath = path.join(baseDir, filename); |
| 56 | + fs.readFile(filePath, 'utf-8', (err, content) => { |
| 57 | + if (err) { |
| 58 | + console.error(`[watch] Failed to read ${filename}:`, err); |
| 59 | + return; |
| 60 | + } |
| 61 | + console.log(`[watch] ${filename} changed (${eventType})`); |
| 62 | + broadcastFileChange(filename, content); |
| 63 | + }); |
| 64 | + } |
| 65 | +}); |
| 66 | + |
| 67 | +// HTTP server |
| 68 | +const server = http.createServer((req, res) => { |
| 69 | + // SSE endpoint |
| 70 | + if (req.url === '/events') { |
| 71 | + res.writeHead(200, { |
| 72 | + 'Content-Type': 'text/event-stream', |
| 73 | + 'Cache-Control': 'no-cache', |
| 74 | + 'Connection': 'keep-alive', |
| 75 | + }); |
| 76 | + res.write('\n'); |
| 77 | + clients.push(res); |
| 78 | + |
| 79 | + console.log('[SSE] Client connected'); |
| 80 | + |
| 81 | + req.on('close', () => { |
| 82 | + console.log('[SSE] Client disconnected'); |
| 83 | + const idx = clients.indexOf(res); |
| 84 | + if (idx !== -1) clients.splice(idx, 1); |
| 85 | + }); |
| 86 | + return; |
| 87 | + } |
| 88 | + |
| 89 | + // Strip query string/hash |
| 90 | + const cleanUrl = req.url.split('?')[0].split('#')[0]; |
| 91 | + let filePath = path.join(baseDir, cleanUrl); |
| 92 | + |
| 93 | + // Serve preloaded index.html instantly for root |
| 94 | + if (cleanUrl === '/' || cleanUrl === '') { |
| 95 | + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); |
| 96 | + res.end(indexHTML); |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + // Prevent directory traversal |
| 101 | + if (!filePath.startsWith(baseDir)) { |
| 102 | + res.writeHead(403); |
| 103 | + res.end('Forbidden'); |
| 104 | + return; |
| 105 | + } |
| 106 | + |
| 107 | + // Serve static files or SPA fallback |
| 108 | + fs.stat(filePath, (err, stats) => { |
| 109 | + if (err || !stats.isFile()) { |
| 110 | + // SPA fallback: serve cached index.html |
| 111 | + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); |
| 112 | + res.end(indexHTML); |
| 113 | + return; |
| 114 | + } |
| 115 | + |
| 116 | + const ext = path.extname(filePath).toLowerCase(); |
| 117 | + const contentType = mimeTypes[ext] || 'application/octet-stream'; |
| 118 | + res.writeHead(200, { 'Content-Type': contentType }); |
| 119 | + fs.createReadStream(filePath).pipe(res); |
| 120 | + }); |
| 121 | +}); |
| 122 | + |
| 123 | +server.listen(PORT, () => { |
| 124 | + console.log(`Server running at http://localhost:${PORT}`); |
| 125 | +}); |
0 commit comments