static-preview.cjs 963 B

1234567891011121314151617181920212223242526
  1. const http = require('http');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const root = path.resolve(__dirname, '..', 'dist', 'frontend', 'browser');
  5. const port = Number(process.env.PORT || 4301);
  6. const types = {
  7. '.html': 'text/html; charset=utf-8',
  8. '.js': 'text/javascript; charset=utf-8',
  9. '.css': 'text/css; charset=utf-8',
  10. '.ico': 'image/x-icon'
  11. };
  12. http.createServer((req, res) => {
  13. const urlPath = decodeURIComponent((req.url || '/').split('?')[0]);
  14. const candidate = path.join(root, urlPath === '/' ? 'index.html' : urlPath);
  15. const safePath = candidate.startsWith(root) && fs.existsSync(candidate) && fs.statSync(candidate).isFile()
  16. ? candidate
  17. : path.join(root, 'index.html');
  18. res.setHeader('Content-Type', types[path.extname(safePath)] || 'application/octet-stream');
  19. fs.createReadStream(safePath).pipe(res);
  20. }).listen(port, '127.0.0.1', () => {
  21. console.log(`Static preview ready: http://127.0.0.1:${port}`);
  22. });