preview-server.mjs 1.1 KB

1234567891011121314151617181920212223242526272829
  1. import { createReadStream, existsSync, statSync } from 'node:fs';
  2. import { createServer } from 'node:http';
  3. import { extname, join, normalize } from 'node:path';
  4. const root = process.cwd();
  5. const port = Number(process.env.PORT || 4173);
  6. const mime = {
  7. '.html': 'text/html; charset=utf-8',
  8. '.js': 'text/javascript; charset=utf-8',
  9. '.css': 'text/css; charset=utf-8',
  10. '.json': 'application/json; charset=utf-8',
  11. '.png': 'image/png'
  12. };
  13. createServer((req, res) => {
  14. const raw = decodeURIComponent((req.url || '/').split('?')[0]);
  15. const safe = normalize(raw).replace(/^(\.\.[/\\])+/, '');
  16. let file = join(root, safe === '/' ? '/web/index.html' : safe);
  17. if (existsSync(file) && statSync(file).isDirectory()) file = join(file, 'index.html');
  18. if (!existsSync(file)) {
  19. res.writeHead(404);
  20. res.end('Not found');
  21. return;
  22. }
  23. res.writeHead(200, { 'content-type': mime[extname(file)] || 'application/octet-stream' });
  24. createReadStream(file).pipe(res);
  25. }).listen(port, () => {
  26. console.log(`Steel Assault Rift preview: http://localhost:${port}/web/index.html`);
  27. });