All source files

scripts/serve.mjs

Download raw file

import {createServer} from 'node:http';
import {readFile, stat} from 'node:fs/promises';
import {dirname, join, normalize} from 'node:path';
import {fileURLToPath} from 'node:url';

const root = join(dirname(fileURLToPath(import.meta.url)),'../dist');
const port = Number(process.env.PORT || 4173);
const types = {'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.txt':'text/plain; charset=utf-8','.xml':'application/xml; charset=utf-8'};

createServer(async (request,response)=>{
  try {
    const pathname = decodeURIComponent(new URL(request.url,'http://localhost').pathname);
    let path = normalize(join(root,pathname));
    if (!path.startsWith(root)) {response.writeHead(403);response.end('Forbidden');return;}
    if ((await stat(path)).isDirectory()) path = join(path,'index.html');
    const body = await readFile(path);
    const extension = path.slice(path.lastIndexOf('.'));
    response.writeHead(200,{'Content-Type':types[extension] || 'application/octet-stream','Cache-Control':'no-store'});
    response.end(body);
  } catch {
    response.writeHead(404,{'Content-Type':'text/plain; charset=utf-8'});response.end('Not found');
  }
}).listen(port,'127.0.0.1',()=>console.log(`WordHint Lab dist preview: http://127.0.0.1:${port}/`));