20 lines
1.2 KiB
JavaScript
20 lines
1.2 KiB
JavaScript
import { createServer } from 'node:http';
|
|
import { readFile } from 'node:fs/promises';
|
|
import { compileContent } from './content.mjs';
|
|
const port = Number(process.env.PORT || 4173);
|
|
const files = new Map([['/', 'index.html'], ['/index.html', 'index.html'], ['/styles.css', 'styles.css'], ['/app.js', 'app.js'], ['/content.js', 'content.js'], ['/favicon.svg', 'favicon.svg']]);
|
|
const mime = { html: 'text/html', css: 'text/css', js: 'text/javascript', svg: 'image/svg+xml' };
|
|
const server = createServer(async (req, res) => {
|
|
let pathname;
|
|
try { pathname = new URL(req.url, 'http://localhost').pathname; }
|
|
catch { res.writeHead(400); return res.end('Bad request'); }
|
|
const file = files.get(pathname);
|
|
if (!file) { res.writeHead(404); return res.end('Not found'); }
|
|
try {
|
|
const body = file === 'content.js' ? await compileContent() : await readFile(new URL(`../${file}`, import.meta.url));
|
|
res.writeHead(200, { 'Content-Type': `${mime[file.split('.').pop()]}; charset=utf-8`, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
|
|
res.end(body);
|
|
} catch { res.writeHead(500); res.end('Unable to read file'); }
|
|
}).listen(port, '127.0.0.1', () => console.log(`Local: http://127.0.0.1:${server.address().port}`));
|
|
|