- 数据分层:base/experiences(事实) + companies(企业维度) + roles(岗位维度) + variants(变体覆盖),Handlebars 模板构建生成 4 份 HTML + 4 份纯文本 + 导航页
- 路由:根路由导航页(默认推荐 私企-全栈),/private/{dev,support}、/soe/{dev,support},旧地址 301 兼容
- 支持/交付岗不改写经历 bullet(与私企-dev 逐字一致),仅专业技能适配
- 移除 CSDN 与文档站链接
- 样式拆分 base + theme-private/theme-soe,打印样式去底色、条目不跨页
- Docker 多阶段构建(node 构建 → nginx 托管),新增 check.mjs 自检与 serve.mjs 本地预览
- 删除旧手写简历(resume/soe/other/txt)与重复样式
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
// scripts/build.mjs —— 构建入口:合并数据 → 渲染 HTML + 纯文本 → 输出 dist/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import Handlebars from 'handlebars';
|
||||
import { ROOT, DIST, loadAll, buildView, buildNav, banner } from './lib.mjs';
|
||||
|
||||
// ---------- Handlebars 辅助 ----------
|
||||
const esc = (s) => Handlebars.escapeExpression(s ?? '');
|
||||
Handlebars.registerHelper('br', (arr) => new Handlebars.SafeString((arr || []).map((x) => esc(x)).join('<br>')));
|
||||
Handlebars.registerHelper('nl', (arr) => (arr || []).join('\n'));
|
||||
Handlebars.registerHelper('joinComma', (arr) => (arr || []).join(', '));
|
||||
Handlebars.registerHelper('add1', (i) => Number(i) + 1);
|
||||
|
||||
// ---------- 模板(txt 模板关闭 HTML 转义) ----------
|
||||
const tplCache = new Map();
|
||||
function tpl(rel) {
|
||||
if (!tplCache.has(rel)) {
|
||||
const file = path.join(ROOT, 'templates', rel);
|
||||
const isTxt = rel.includes('/txt/') || rel.endsWith('.txt.hbs');
|
||||
tplCache.set(rel, Handlebars.compile(fs.readFileSync(file, 'utf8'), { strict: false, noEscape: isTxt }));
|
||||
}
|
||||
return tplCache.get(rel);
|
||||
}
|
||||
|
||||
function writeOut(rel, content) {
|
||||
const file = path.join(DIST, rel);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, content);
|
||||
}
|
||||
|
||||
// ---------- 构建 ----------
|
||||
const data = loadAll();
|
||||
const views = data.variants.map((v) => buildView(v, data));
|
||||
const matrix = buildNav(views);
|
||||
const navCtx = {
|
||||
name: data.base.name,
|
||||
contact: data.base.contact,
|
||||
links: data.base.links || [],
|
||||
site: data.base.site,
|
||||
matrix,
|
||||
views,
|
||||
};
|
||||
|
||||
const pageTpl = tpl('page.html.hbs');
|
||||
const resumeTxtTpl = tpl('resume.txt.hbs');
|
||||
|
||||
for (const view of views) {
|
||||
// HTML:逐板块渲染后拼装(第一板块为基本信息 header)
|
||||
const rendered = view.sections.map((s) => ({
|
||||
id: s.id,
|
||||
html: tpl(`html/${s.html}.hbs`)(s.ctx),
|
||||
}));
|
||||
const headerHtml = rendered[0].html;
|
||||
const bodyHtml = rendered.slice(1).map((r) => r.html).join('\n');
|
||||
const html = pageTpl({
|
||||
meta: view.meta,
|
||||
theme: view.theme,
|
||||
selfUrl: view.selfUrl,
|
||||
baseUrl: view.merged.site.baseUrl,
|
||||
txtUrl: view.txtPath,
|
||||
headerHtml,
|
||||
bodyHtml,
|
||||
});
|
||||
writeOut(path.join(view.companyId, view.roleId, 'index.html'), html);
|
||||
|
||||
// 纯文本:逐板块渲染 + 横幅标题(板块间空一行)
|
||||
const blocks = view.sections.map((s) => banner(s.title) + tpl(`txt/${s.txt}.txt.hbs`)(s.ctx).trimEnd() + '\n\n');
|
||||
const txt = resumeTxtTpl({ sections: blocks }).trimEnd() + '\n';
|
||||
writeOut(path.join('txt', view.companyId, view.roleId, 'index.txt'), txt);
|
||||
}
|
||||
|
||||
// 导航页与纯文本选择页
|
||||
writeOut('index.html', tpl('nav.html.hbs')(navCtx));
|
||||
writeOut('txt/index.html', tpl('txt-index.html.hbs')(navCtx));
|
||||
|
||||
// 静态资源
|
||||
fs.cpSync(path.join(ROOT, 'css'), path.join(DIST, 'css'), { recursive: true });
|
||||
fs.cpSync(path.join(ROOT, 'img'), path.join(DIST, 'img'), { recursive: true });
|
||||
|
||||
console.log(`构建完成:${views.length} 份简历(HTML + txt)+ 导航页 → ${path.relative(ROOT, DIST)}/`);
|
||||
for (const v of views) {
|
||||
console.log(` ${v.path.padEnd(20)} ${v.meta.title}${v.isDefault ? '(默认)' : ''}`);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// scripts/check.mjs —— 构建自检:必填字段、跨层同键、占位符残留、产物完整性
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { ROOT, DIST, loadAll, buildView, SECTION_REGISTRY, keyPaths, isObj } from './lib.mjs';
|
||||
|
||||
const errors = [];
|
||||
const warnings = [];
|
||||
const err = (m) => errors.push(m);
|
||||
const warn = (m) => warnings.push(m);
|
||||
|
||||
const data = loadAll();
|
||||
const views = [];
|
||||
|
||||
// 1. 视图构建 + 必填字段
|
||||
for (const v of data.variants) {
|
||||
const label = `${v.company}-${v.role}`;
|
||||
let view;
|
||||
try {
|
||||
view = buildView(v, data);
|
||||
} catch (e) {
|
||||
err(`[${label}] 视图构建失败:${e.message}`);
|
||||
continue;
|
||||
}
|
||||
views.push(view);
|
||||
const m = view.merged;
|
||||
for (const [key, val] of [
|
||||
['name', m.name],
|
||||
['contact.phone', m.contact && m.contact.phone],
|
||||
['contact.email', m.contact && m.contact.email],
|
||||
['education.school', m.education && m.education.school],
|
||||
['education.major', m.education && m.education.major],
|
||||
['site.baseUrl', m.site && m.site.baseUrl],
|
||||
]) {
|
||||
if (!val) err(`[${label}] 缺少必填字段 ${key}`);
|
||||
}
|
||||
if (!v.sections || !v.sections.length) err(`[${label}] 未声明任何板块`);
|
||||
if (!v.meta || !v.meta.title) warn(`[${label}] 未设置 meta.title,将使用默认标题`);
|
||||
if (!v.meta || !v.meta.description) warn(`[${label}] 未设置 meta.description`);
|
||||
|
||||
// 板块内引用的经历 id 必须存在
|
||||
const expIds = new Set(Object.keys(m.experiences || {}));
|
||||
for (const [orderKey, ids] of Object.entries(m.order || {})) {
|
||||
for (const id of ids) if (!expIds.has(id)) err(`[${label}] order.${orderKey} 引用了不存在的经历 "${id}"`);
|
||||
}
|
||||
for (const [id, exp] of Object.entries(m.experiences || {})) {
|
||||
if (exp && exp.bullets && !exp.bullets.length) warn(`[${label}] ${id} 的 bullets 为空`);
|
||||
if (exp && exp.bullets === undefined && (exp.kind === 'internship' || exp.kind === 'project')) {
|
||||
warn(`[${label}] ${id} 缺少 bullets(是否遗漏岗位维度内容?)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 跨层同键检查(同一字段改了一层、被另一层覆盖的风险)
|
||||
// 仅对比「内容层」:companies/<x>.yaml 与 roles/<y>.yaml 的键路径交集
|
||||
const META_KEYS = new Set(['navLabel', 'theme']);
|
||||
for (const [cname, company] of Object.entries(data.companies)) {
|
||||
for (const [rname, role] of Object.entries(data.roles)) {
|
||||
const a = keyPaths(company);
|
||||
const b = keyPaths(role);
|
||||
for (const p of a) {
|
||||
if (b.has(p) && !META_KEYS.has(p.split('.')[0])) {
|
||||
warn(`companies/${cname}.yaml 与 roles/${rname}.yaml 同时定义了 "${p}"(合并时 roles 层覆盖 companies 层,请确认是否有意)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 变体覆盖数量提醒(防 override 滥用导致"维度共享"失效)
|
||||
for (const v of data.variants) {
|
||||
const n = keyPaths(v.overrides || {}).size;
|
||||
if (n > 12) warn(`[variants] ${v.company}-${v.role} 的 overrides 有 ${n} 个字段,数量偏多,请确认是否应下沉到维度层`);
|
||||
}
|
||||
|
||||
// 3. dist 产物检查
|
||||
const expected = [];
|
||||
for (const v of views) {
|
||||
expected.push(path.join(v.companyId, v.roleId, 'index.html'));
|
||||
expected.push(path.join('txt', v.companyId, v.roleId, 'index.txt'));
|
||||
}
|
||||
expected.push('index.html', 'txt/index.html', 'css/base.css', 'css/theme-private.css', 'css/theme-soe.css', 'css/nav.css');
|
||||
|
||||
for (const rel of expected) {
|
||||
if (!fs.existsSync(path.join(DIST, rel))) err(`缺少构建产物 dist/${rel.replace(/\\/g, '/')}`);
|
||||
}
|
||||
|
||||
const LEAK = /\{\{|\}\}|undefined|\[object Object\]|(^|[^A-Za-z])NaN([^A-Za-z]|$)/;
|
||||
const titles = new Set();
|
||||
for (const rel of expected.filter((f) => /\.(html|txt)$/.test(f))) {
|
||||
const file = path.join(DIST, rel);
|
||||
if (!fs.existsSync(file)) continue;
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
const m = text.match(LEAK);
|
||||
if (m) err(`dist/${rel.replace(/\\/g, '/')} 疑似模板残留或非法值:"${m[0]}"`);
|
||||
if (rel.endsWith('.html') && rel !== 'index.html' && rel !== 'txt/index.html') {
|
||||
const t = text.match(/<title>([^<]+)<\/title>/);
|
||||
if (t) titles.add(t[1]);
|
||||
}
|
||||
if (rel.endsWith('.txt') && !text.includes('【基本信息】')) err(`dist/${rel.replace(/\\/g, '/')} 缺少【基本信息】段`);
|
||||
}
|
||||
if (views.length && titles.size !== views.length) err(`简历页 <title> 不唯一(${titles.size} 个不同标题 / ${views.length} 份简历)`);
|
||||
|
||||
// ---------- 汇总 ----------
|
||||
for (const w of warnings) console.log(`[警告] ${w}`);
|
||||
for (const e of errors) console.log(`[错误] ${e}`);
|
||||
console.log(`检查完成:${views.length} 份视图,${errors.length} 个错误,${warnings.length} 个警告`);
|
||||
if (errors.length) process.exit(1);
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
// scripts/lib.mjs —— 数据加载、分层合并、视图构建(build.mjs 与 check.mjs 共用)
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import YAML from 'yaml';
|
||||
|
||||
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
export const DIST = path.join(ROOT, 'dist');
|
||||
|
||||
export const CIRCLED = ['①', '②', '③', '④', '⑤'];
|
||||
|
||||
const BANNER_WIDTH = 80;
|
||||
export const banner = (title) =>
|
||||
`${'='.repeat(BANNER_WIDTH)}\n【${title}】\n${'='.repeat(BANNER_WIDTH)}\n\n`;
|
||||
|
||||
// ---------- 数据加载 ----------
|
||||
export function readYaml(rel) {
|
||||
return YAML.parse(fs.readFileSync(path.join(ROOT, rel), 'utf8'));
|
||||
}
|
||||
|
||||
function stem(f) {
|
||||
return f.replace(/\.ya?ml$/i, '');
|
||||
}
|
||||
|
||||
export function keyByStem(rel) {
|
||||
const dir = path.join(ROOT, rel);
|
||||
const out = {};
|
||||
for (const f of fs.readdirSync(dir).filter((x) => /\.ya?ml$/i.test(x)).sort()) {
|
||||
out[stem(f)] = YAML.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function loadAll() {
|
||||
const base = readYaml('data/base.yaml');
|
||||
const expMap = keyByStem('data/experiences');
|
||||
base.experiences = expMap;
|
||||
return {
|
||||
base,
|
||||
companies: keyByStem('data/companies'),
|
||||
roles: keyByStem('data/roles'),
|
||||
variants: Object.values(keyByStem('data/variants')),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- 深合并(对象合并,数组整体替换,后层覆盖前层) ----------
|
||||
export const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
export function deepMerge(a, b) {
|
||||
if (b === undefined) return a;
|
||||
if (Array.isArray(b) || Array.isArray(a)) return b;
|
||||
if (isObj(a) && isObj(b)) {
|
||||
const out = { ...a };
|
||||
for (const k of Object.keys(b)) out[k] = deepMerge(a[k], b[k]);
|
||||
return out;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// 递归收集对象键路径(数组视为叶子),用于跨层同键检查
|
||||
export function keyPaths(obj, prefix = '', out = new Set()) {
|
||||
if (!isObj(obj)) return out;
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
const p = prefix ? `${prefix}.${k}` : k;
|
||||
if (isObj(v)) keyPaths(v, p, out);
|
||||
else out.add(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- 工具 ----------
|
||||
export function normalizeList(items) {
|
||||
return (items || []).map((it) => (typeof it === 'string' ? { text: it } : { ...it }));
|
||||
}
|
||||
|
||||
function orderedExperiences(merged, kind, orderKey) {
|
||||
const all = Object.values(merged.experiences || {}).filter((e) => e && e.kind === kind);
|
||||
const order = (merged.order && merged.order[orderKey]) || [];
|
||||
const listed = order.map((id) => all.find((e) => e.id === id)).filter(Boolean);
|
||||
const rest = all.filter((e) => !order.includes(e.id));
|
||||
return [...listed, ...rest];
|
||||
}
|
||||
|
||||
// ---------- 板块注册表:板块 id → 标题 / html 模板 / txt 模板 ----------
|
||||
export const SECTION_REGISTRY = {
|
||||
education: { title: '教育经历', html: 'education', txt: 'education' },
|
||||
honors: { title: '荣誉奖项', html: 'honors', txt: 'honors' },
|
||||
internships: { title: '实习经历', html: 'entries', txt: 'entries' },
|
||||
campus: { title: '校园经历', html: 'campus', txt: 'campus' },
|
||||
projects: { title: '项目经历', html: 'projects', txt: 'projects' },
|
||||
certificates: { title: '证书', html: 'simple-list', txt: 'simple-list', listClass: 'exp-items' },
|
||||
studentWork: { title: '学生工作', html: 'student-work', txt: 'student-work' },
|
||||
socialPractice: { title: '社会实践', html: 'social-practice', txt: 'social-practice' },
|
||||
skills: { title: '专业技能', html: 'simple-list', txt: 'simple-list', listClass: 'skill-items', sep: ': ' },
|
||||
selfEval: { title: '自我评价', html: 'simple-list', txt: 'simple-list', listClass: 'skill-items', sep: ':' },
|
||||
};
|
||||
|
||||
// ---------- 变体视图构建 ----------
|
||||
export function buildView(v, data) {
|
||||
const company = data.companies[v.company];
|
||||
const role = data.roles[v.role];
|
||||
if (!company) throw new Error(`变体 ${v.company}-${v.role} 引用了未知企业维度 "${v.company}"`);
|
||||
if (!role) throw new Error(`变体 ${v.company}-${v.role} 引用了未知岗位维度 "${v.role}"`);
|
||||
|
||||
// 合并优先级:base → companies → roles → variants.overrides
|
||||
const merged = deepMerge(deepMerge(deepMerge(data.base, company), role), v.overrides || {});
|
||||
|
||||
const variantPath = `/${v.company}/${v.role}`;
|
||||
const selfUrl = `${merged.site.baseUrl}${variantPath}`;
|
||||
|
||||
const intentParts = (merged.intent || []).map((text, i) => ({ num: CIRCLED[i] || `${i + 1}.`, text }));
|
||||
const links = [
|
||||
{ label: '线上简历', url: selfUrl, display: selfUrl },
|
||||
...(merged.links || []).map((l) => ({ ...l, display: l.text || l.url })),
|
||||
];
|
||||
const headerCfg = merged.header || {};
|
||||
const header = {
|
||||
layout: headerCfg.layout === 'formal' ? 'formal' : 'compact',
|
||||
photo: merged.photo || null,
|
||||
politicalStatus: merged.politicalStatus || null,
|
||||
headline: merged.headline || null,
|
||||
intentParts,
|
||||
intentLine: intentParts.map((p) => `${p.num} ${p.text}`).join(' '),
|
||||
techTags: merged.techTags || [],
|
||||
techTagsText: (merged.techTags || []).join(', '),
|
||||
showLinks: headerCfg.showLinks !== false,
|
||||
showExpCert: headerCfg.showExpCert !== false,
|
||||
links,
|
||||
};
|
||||
|
||||
// 荣誉:展示方式与筛选由企业维度 honorDisplay 控制
|
||||
const hd = merged.honorDisplay || {};
|
||||
let honors = (merged.honors || []).map((h) => ({ ...h }));
|
||||
if (Array.isArray(hd.show) && hd.show.length) {
|
||||
honors = hd.show.map((id) => honors.find((h) => h.id === id)).filter(Boolean);
|
||||
}
|
||||
const honorsView = {
|
||||
honors,
|
||||
left: honors.filter((h) => h.cert),
|
||||
right: honors.filter((h) => !h.cert),
|
||||
layoutTwoCol: hd.layout === 'two-col',
|
||||
showDate: hd.display === 'date',
|
||||
};
|
||||
|
||||
const projCfg = merged.projects || {};
|
||||
const baseCtx = { ...merged, header, title: '', listClass: '', sep: '' };
|
||||
const camp = orderedExperiences(merged, 'camp', 'campus')[0] || null;
|
||||
|
||||
// 基本信息(header)恒为第一板块,模板按企业维度版式选择
|
||||
const headerSection = {
|
||||
id: 'header',
|
||||
title: '基本信息',
|
||||
html: `header-${header.layout}`,
|
||||
txt: `header-${header.layout}`,
|
||||
ctx: { ...baseCtx, title: '基本信息' },
|
||||
};
|
||||
|
||||
const contentSections = (v.sections || []).map((id) => {
|
||||
const reg = SECTION_REGISTRY[id];
|
||||
if (!reg) throw new Error(`变体 ${v.company}-${v.role} 声明了未知板块 "${id}"`);
|
||||
const common = { ...baseCtx, title: reg.title, listClass: reg.listClass || 'skill-items', sep: reg.sep || ':' };
|
||||
switch (id) {
|
||||
case 'education':
|
||||
return { id, ...reg, ctx: common };
|
||||
case 'honors':
|
||||
return { id, ...reg, ctx: { ...common, ...honorsView } };
|
||||
case 'internships':
|
||||
return {
|
||||
id, ...reg,
|
||||
ctx: {
|
||||
...common,
|
||||
items: orderedExperiences(merged, 'internship', 'internships').map((e) => ({ ...e, bullets: e.bullets || [] })),
|
||||
},
|
||||
};
|
||||
case 'projects':
|
||||
return {
|
||||
id, ...reg,
|
||||
ctx: {
|
||||
...common,
|
||||
projIntroDashed: projCfg.introStyle === 'dashed',
|
||||
showWorkTitle: projCfg.showWorkTitle === true,
|
||||
items: orderedExperiences(merged, 'project', 'projects').map((e) => ({ ...e, bullets: e.bullets || [] })),
|
||||
},
|
||||
};
|
||||
case 'campus':
|
||||
return { id, ...reg, ctx: { ...common, line: (merged.campus && merged.campus.line) || [], featured: camp } };
|
||||
case 'certificates':
|
||||
return { id, ...reg, ctx: { ...common, items: normalizeList(merged.certificates) } };
|
||||
case 'studentWork':
|
||||
return { id, ...reg, ctx: { ...common, items: merged.studentWork || [] } };
|
||||
case 'socialPractice':
|
||||
return { id, ...reg, ctx: { ...common, practice: merged.socialPractice || {} } };
|
||||
case 'skills':
|
||||
case 'selfEval':
|
||||
return { id, ...reg, ctx: { ...common, items: normalizeList(merged[id]) } };
|
||||
default:
|
||||
return { id, ...reg, ctx: common };
|
||||
}
|
||||
});
|
||||
|
||||
const meta = v.meta || {};
|
||||
const title = meta.title || `何朝晖 · ${role.navLabel}(${company.navLabel}版)`;
|
||||
const description = meta.description || `${merged.name}个人简历 - ${role.navLabel}(${company.navLabel}投递版)`;
|
||||
|
||||
return {
|
||||
id: `${v.company}-${v.role}`,
|
||||
companyId: v.company,
|
||||
roleId: v.role,
|
||||
company,
|
||||
role,
|
||||
path: `${variantPath}/`,
|
||||
txtPath: `/txt${variantPath}`,
|
||||
selfUrl,
|
||||
theme: company.theme || v.company,
|
||||
meta: { title, description },
|
||||
nav: v.nav || {},
|
||||
isDefault: v.default === true,
|
||||
merged,
|
||||
header,
|
||||
honors: honorsView,
|
||||
sections: [headerSection, ...contentSections],
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- 导航矩阵 ----------
|
||||
function orderIdx(list, x) {
|
||||
const i = list.indexOf(x);
|
||||
return i === -1 ? 99 : i;
|
||||
}
|
||||
|
||||
export function buildNav(views) {
|
||||
const companyOrder = ['private', 'soe'];
|
||||
const roleOrder = ['dev', 'support'];
|
||||
const companies = [...new Set(views.map((v) => v.companyId))].sort((a, b) => orderIdx(companyOrder, a) - orderIdx(companyOrder, b));
|
||||
const roles = [...new Set(views.map((v) => v.roleId))].sort((a, b) => orderIdx(roleOrder, a) - orderIdx(roleOrder, b));
|
||||
return {
|
||||
companies: companies.map((c) => ({ id: c, navLabel: views.find((v) => v.companyId === c).company.navLabel })),
|
||||
rows: roles.map((r) => ({
|
||||
id: r,
|
||||
navLabel: views.find((v) => v.roleId === r).role.navLabel,
|
||||
cells: companies
|
||||
.map((c) => views.find((v) => v.companyId === c && v.roleId === r))
|
||||
.filter(Boolean),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// 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/)`));
|
||||
Reference in New Issue
Block a user