Files
ascii-pwa/serve.mjs
T
2026-10-10 12:51:33 +02:00

37 lines
1.5 KiB
JavaScript

// Development server only. Deploy the frontend files to any HTTPS static host.
import http from 'node:http';
import {readFile} from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
const root = path.dirname(fileURLToPath(import.meta.url));
const types = {
'.html': 'text/html; charset=utf-8', '.js': 'application/javascript',
'.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png',
'.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2',
};
const port = Number(process.env.PORT || 8080);
http.createServer(async (request, response) => {
try {
const url = new URL(request.url, 'http://localhost');
const filename = decodeURIComponent(url.pathname);
const target = path.resolve(root, `.${filename === '/' ? '/index.html' : filename}`);
if (!target.startsWith(root + path.sep)) {
response.writeHead(403).end();
return;
}
if (!['GET', 'HEAD'].includes(request.method)) {
response.writeHead(405, {Allow: 'GET, HEAD'}).end();
return;
}
const content = await readFile(target);
response.writeHead(200, {
'Content-Type': types[path.extname(target)] || 'application/octet-stream',
'Cache-Control': 'no-cache',
});
response.end(request.method === 'HEAD' ? undefined : content);
} catch {
response.writeHead(404).end('Not found');
}
}).listen(port, '127.0.0.1', () => console.log(`ascii: http://localhost:${port}`));