| 12345678910111213141516171819202122232425262728293031 |
- import { createServer } from 'node:http';
- import { readFile } from 'node:fs/promises';
- import { dirname, extname, resolve, sep } from 'node:path';
- import { fileURLToPath } from 'node:url';
- const root = dirname(fileURLToPath(import.meta.url));
- const port = Number(process.env.DEMO_PORT || 4300);
- 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' };
- createServer(async (request, response) => {
- try {
- const url = new URL(request.url, `http://localhost:${port}`);
- const pathname = decodeURIComponent(url.pathname);
- const path = resolve(root, '.' + pathname);
- if (path !== root && !path.startsWith(root + sep)) {
- response.writeHead(403); response.end('Forbidden'); return;
- }
- const isRoute = !extname(pathname) || pathname === '/';
- const data = await readFile(isRoute ? resolve(root, 'index.html') : path);
- response.writeHead(200, {
- 'Content-Type': isRoute ? types['.html'] : types[extname(path)] || 'application/octet-stream',
- 'Cache-Control': 'no-store',
- 'X-Content-Type-Options': 'nosniff',
- 'Referrer-Policy': 'no-referrer',
- });
- response.end(data);
- } catch {
- response.writeHead(404); response.end('Not found');
- }
- }).listen(port, '0.0.0.0', () => {
- process.stdout.write(`Fmode design demo: http://localhost:${port}\n`);
- });
|