preview.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { createServer } from 'node:http';
  2. import { readFile, stat } from 'node:fs/promises';
  3. import path from 'node:path';
  4. import { fileURLToPath } from 'node:url';
  5. const root = path.dirname(fileURLToPath(import.meta.url));
  6. const port = Number(process.env.PORT || 4176);
  7. const mimeTypes = {
  8. '.html': 'text/html; charset=utf-8',
  9. '.css': 'text/css; charset=utf-8',
  10. '.js': 'text/javascript; charset=utf-8',
  11. '.mjs': 'text/javascript; charset=utf-8',
  12. '.png': 'image/png',
  13. '.md': 'text/plain; charset=utf-8',
  14. };
  15. createServer(async (request, response) => {
  16. try {
  17. const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
  18. const filename = path.resolve(root, `.${pathname === '/' ? '/index.html' : pathname}`);
  19. if (!filename.startsWith(root + path.sep)) {
  20. response.writeHead(403).end('Forbidden');
  21. return;
  22. }
  23. if (!(await stat(filename)).isFile()) throw new Error('Not a file');
  24. const content = await readFile(filename);
  25. response.writeHead(200, {
  26. 'Content-Type': mimeTypes[path.extname(filename)] || 'application/octet-stream',
  27. 'Cache-Control': 'no-store',
  28. 'X-Content-Type-Options': 'nosniff',
  29. });
  30. response.end(content);
  31. } catch {
  32. response.writeHead(404).end('Not found');
  33. }
  34. }).listen(port, '127.0.0.1', () => {
  35. console.log(`Prototype: http://127.0.0.1:${port}/#/chat/c1`);
  36. });