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