serve.mjs 1.1 KB

12345678910111213
  1. import http from 'node:http';
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import {fileURLToPath} from 'node:url';
  5. const root=path.dirname(fileURLToPath(import.meta.url));
  6. const mime={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.png':'image/png','.svg':'image/svg+xml','.ttf':'font/ttf','.txt':'text/plain; charset=utf-8'};
  7. const port=Number(process.env.BUFFALO_PREVIEW_PORT||4318);
  8. http.createServer((req,res)=>{
  9. let pathname;try{pathname=decodeURIComponent(new URL(req.url,'http://localhost').pathname);}catch{res.writeHead(400).end();return;}
  10. const file=path.resolve(root,'.'+(pathname==='/'?'/index.html':pathname));
  11. if(file!==root&&!file.startsWith(root+path.sep)){res.writeHead(403).end();return;}
  12. fs.stat(file,(err,stat)=>{if(err||!stat.isFile()){res.writeHead(404).end('Not found');return;}res.writeHead(200,{'Content-Type':mime[path.extname(file)]||'application/octet-stream','Cache-Control':'no-cache'});fs.createReadStream(file).pipe(res);});
  13. }).listen(port,'127.0.0.1',()=>console.log('Buffalo Siege preview: http://127.0.0.1:'+port));