Files
resume/scripts/serve.mjs
T

75 lines
2.5 KiB
JavaScript
Raw Normal View History

// scripts/serve.mjs —— 本地预览静态服务器(模拟 nginx 路由,含旧地址 301)
// 也导出 createStaticServer() 供 scripts/pdf.mjs 在构建期复用
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { DIST } from './lib.mjs';
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',
'.pdf': 'application/pdf',
};
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));
}
export function createStaticServer(root = DIST) {
return 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(root, 'txt', txtMatch[1], txtMatch[2], 'index.txt'));
if (p === '/txt') return send(res, path.join(root, 'txt', 'index.html'));
let file = path.join(root, 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);
});
}
// 直接运行时启动预览服务
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const PORT = Number(process.env.PORT || 4173);
createStaticServer().listen(PORT, () => console.log(`本地预览:http://localhost:${PORT}/ (dist/)`));
}