8 lines
1022 B
JavaScript
8 lines
1022 B
JavaScript
import http from 'node:http';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
const root=path.resolve(process.env.PREVIEW_DIR||'dist');
|
|
if(!fs.existsSync(path.join(root,'index.html')))throw Error('请先运行 npm run build,再启动预览。');
|
|
const mime={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.json':'application/json'};
|
|
http.createServer((req,res)=>{let p;try{p=decodeURIComponent(new URL(req.url,'http://localhost').pathname);}catch{res.writeHead(400).end();return;}const file=path.resolve(root,'.'+(p==='/'?'/index.html':p));if(!file.startsWith(root+path.sep)){res.writeHead(403).end();return;}fs.readFile(file,(err,b)=>{if(err){res.writeHead(404).end('Not found');return;}res.writeHead(200,{'Content-Type':mime[path.extname(file)]||'application/octet-stream','Cache-Control':'no-store'});res.end(b);});}).listen(4173,'127.0.0.1',()=>console.log('山河拼图预览:http://localhost:4173'));
|