← back to Re Flyer Aggregator

serve-viewers.mjs

17 lines

import http from 'node:http'; import { readFileSync, statSync } from 'node:fs'; import { join, extname, dirname } from 'node:path'; import { fileURLToPath } from 'node:url';
const PUB = join(dirname(fileURLToPath(import.meta.url)), 'public');
const MIME = {'.html':'text/html','.json':'application/json','.csv':'text/csv','.js':'text/javascript','.css':'text/css','.png':'image/png'};
const ROOT = dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 9862;
const ALIAS = { '/':'/sources/index.html', '/sources':'/sources/index.html', '/live.html':'/flyers/live.html',
  '/flyers.json':'/flyers/flyers.json', '/advertising':'/advertising/index.html', '/property-flyers':'/flyers-found/index.html', '/flyers-found':'/flyers-found/index.html', '/flyers':'/flyers/index.html',
  '/search':'/search/index.html', '/deals':'/deals/index.html', '/properties':'/properties/index.html', '/listings':'/search/index.html' };
http.createServer((q,s)=>{
  let u = decodeURIComponent(q.url.split('?')[0]); u = ALIAS[u] || u;
  // the growing article archive lives in data/ (outside public) — serve it for the global search
  let fp = u === '/article-archive.json' ? join(ROOT, 'data', 'article-archive.json') : join(PUB, u);
  try { if (statSync(fp).isDirectory()) fp = join(fp,'index.html'); } catch {}
  try { const b = readFileSync(fp); s.writeHead(200,{'content-type':MIME[extname(fp)]||'text/html','cache-control':'no-store','access-control-allow-origin':'*'}); s.end(b); }
  catch(e){ s.writeHead(404); s.end('not found: '+u); }
}).listen(PORT, ()=>console.log(`viewers :${PORT} — / = sources dashboard, /live.html = viz, /advertising = ad intel`));