68 lines
2.2 KiB
JavaScript
68 lines
2.2 KiB
JavaScript
// scripts/serve.mjs —— 本地预览静态服务器(模拟 nginx 路由,含旧地址 301)
|
||||
|
|
import http from 'node:http';
|
|||
|
|
import fs from 'node:fs';
|
|||
|
|
import path from 'node:path';
|
|||
|
|
import { DIST } from './lib.mjs';
|
|||
|
|
|
|||
|
|
const PORT = Number(process.env.PORT || 4173);
|
|||
|
|
|
|||
|
|
const MIME = {
|
|||
|
|
'.html': 'text/html; charset=utf-8',
|
|||
|
|
'.css': 'text/css; charset=utf-8',
|
|||
|
|
'.js': 'text/javascript; charset=utf-8',
|
|||
|
|
'.svg': 'image/svg+xml',
|
|||
|
|
'.png': 'image/png',
|
|||
|
|
'.jpg': 'image/jpeg',
|
|||
|
|
'.jpeg': 'image/jpeg',
|
|||
|
|
'.gif': 'image/gif',
|
|||
|
|
'.ico': 'image/x-icon',
|
|||
|
|
'.txt': 'text/plain; charset=utf-8',
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
const REDIRECTS = {
|
|||
|
|
'/resume': '/private/dev/',
|
|||
|
|
'/resume/': '/private/dev/',
|
|||
|
|
'/soe': '/soe/dev/',
|
|||
|
|
'/soe/': '/soe/dev/',
|
|||
|
|
'/txt/resume': '/txt/private/dev',
|
|||
|
|
'/txt/soe': '/txt/soe/dev',
|
|||
|
|
'/other': '/',
|
|||
|
|
'/other/': '/',
|
|||
|
|
'/txt/': '/txt',
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
function send(res, file, forceType) {
|
|||
|
|
if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) {
|
|||
|
|
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|||
|
|
return res.end('404 Not Found');
|
|||
|
|
}
|
|||
|
|
const ext = path.extname(file).toLowerCase();
|
|||
|
|
res.writeHead(200, { 'Content-Type': forceType || MIME[ext] || 'application/octet-stream' });
|
|||
|
|
res.end(fs.readFileSync(file));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
http
|
|||
|
|
.createServer((req, res) => {
|
|||
|
|
const p = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
|||
|
|
if (REDIRECTS[p]) {
|
|||
|
|
res.writeHead(301, { Location: REDIRECTS[p] });
|
|||
|
|
return res.end();
|
|||
|
|
}
|
|||
|
|
if (p.startsWith('/other/') || p.startsWith('/resume/')) {
|
|||
|
|
res.writeHead(301, { Location: p.startsWith('/resume/') ? '/private/dev/' : '/' });
|
|||
|
|
return res.end();
|
|||
|
|
}
|
|||
|
|
const txtMatch = p.match(/^\/txt\/(private|soe)\/(dev|support)$/);
|
|||
|
|
if (txtMatch) return send(res, path.join(DIST, 'txt', txtMatch[1], txtMatch[2], 'index.txt'));
|
|||
|
|
if (p === '/txt') return send(res, path.join(DIST, 'txt', 'index.html'));
|
|||
|
|
|
|||
|
|
let file = path.join(DIST, p);
|
|||
|
|
if (p.endsWith('/')) file = path.join(file, 'index.html');
|
|||
|
|
else if (fs.existsSync(file) && fs.statSync(file).isDirectory()) {
|
|||
|
|
res.writeHead(301, { Location: `${p}/` });
|
|||
|
|
return res.end();
|
|||
|
|
}
|
|||
|
|
send(res, file);
|
|||
|
|
})
|
|||
|
|
.listen(PORT, () => console.log(`本地预览:http://localhost:${PORT}/ (dist/)`));
|