server.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031
  1. import { createServer } from 'node:http';
  2. import { readFile } from 'node:fs/promises';
  3. import { dirname, extname, resolve, sep } from 'node:path';
  4. import { fileURLToPath } from 'node:url';
  5. const root = dirname(fileURLToPath(import.meta.url));
  6. const port = Number(process.env.DEMO_PORT || 4300);
  7. const types = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.md': 'text/plain; charset=utf-8', '.json': 'application/json' };
  8. createServer(async (request, response) => {
  9. try {
  10. const url = new URL(request.url, `http://localhost:${port}`);
  11. const pathname = decodeURIComponent(url.pathname);
  12. const path = resolve(root, '.' + pathname);
  13. if (path !== root && !path.startsWith(root + sep)) {
  14. response.writeHead(403); response.end('Forbidden'); return;
  15. }
  16. const isRoute = !extname(pathname) || pathname === '/';
  17. const data = await readFile(isRoute ? resolve(root, 'index.html') : path);
  18. response.writeHead(200, {
  19. 'Content-Type': isRoute ? types['.html'] : types[extname(path)] || 'application/octet-stream',
  20. 'Cache-Control': 'no-store',
  21. 'X-Content-Type-Options': 'nosniff',
  22. 'Referrer-Policy': 'no-referrer',
  23. });
  24. response.end(data);
  25. } catch {
  26. response.writeHead(404); response.end('Not found');
  27. }
  28. }).listen(port, '0.0.0.0', () => {
  29. process.stdout.write(`Fmode design demo: http://localhost:${port}\n`);
  30. });