serve.js (1515B)
1 const http = require('http'); 2 const fs = require('fs'); 3 const path = require('path'); 4 5 const ROOT = path.join(__dirname, '..'); 6 const MIME = { 7 '.html': 'text/html', 8 '.js': 'application/javascript', 9 '.css': 'text/css', 10 '.svg': 'image/svg+xml', 11 '.png': 'image/png', 12 '.webp': 'image/webp', 13 '.mp3': 'audio/mpeg', 14 '.md': 'text/markdown', 15 }; 16 17 function serve(port) { 18 port = port || parseInt(process.env.PORT || '8765'); 19 return new Promise((resolve, reject) => { 20 const server = http.createServer((req, res) => { 21 let urlPath = req.url.split('?')[0]; 22 if (urlPath === '/') urlPath = '/index.html'; 23 // also serve directory index 24 if (!path.extname(urlPath)) urlPath += '/index.html'; 25 const file = path.join(ROOT, urlPath); 26 const ext = path.extname(file); 27 try { 28 const data = fs.readFileSync(file); 29 res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' }); 30 res.end(data); 31 } catch (_) { 32 res.writeHead(404, { 'Content-Type': 'text/plain' }); 33 res.end('not found: ' + urlPath); 34 } 35 }); 36 server.listen(port, '127.0.0.1', () => { 37 resolve({ server, url: `http://127.0.0.1:${port}` }); 38 }); 39 server.on('error', reject); 40 }); 41 } 42 43 if (require.main === module) { 44 serve().then(({ url }) => { 45 console.log(`KGames dev server: ${url}`); 46 process.on('SIGINT', () => process.exit(0)); 47 }).catch(e => { console.error(e); process.exit(1); }); 48 } 49 50 module.exports = serve;