Files
materials/knowledge/linux/tools/build-nav.js
huanghaosheng 3ccd17cad8 refactor: SRE 学习路径抽成独立板块「学习路线」,与知识库同级
- knowledge/sre-learning-path/ -> 学习路线/sre-learning-path/(git mv,404 个文件保留改名历史)
- 导航页新增模块 learning-path(num 03,project 顺延 04),知识库回到 4 份资料
- check-portal.js / add-back-links.js 支持模块目录独立于 id(m.dir || m.id),
  路由仍为 #/learning-path/sre-learning-path,URL 保持 ASCII
- portal.js 快捷键提示按模块数生成、复制板块目录用真实目录名
- docker / linux / nginx 的外链、build-nav.js 生成器与自检白名单改指 ../../学习路线/sre-learning-path/
- 399 个站点页面与全部知识站点的返回入口由 tools/add-back-links.js 重算
  (标签改为「学习路径 › SRE 从零到成熟学习路径」)
- .sre-s23 生成脚手架与根 README、index.html 同步到新路径与新板块数

自检:check-portal / add-back-links --check 全绿;
学习路线站点 399 页与 docker、linux、nginx 的 check-pages 全部通过。
2026-10-14 23:33:29 +08:00

182 lines
8.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/* ==========================================================================
Linux 专题 · 页面骨架生成器
用法:node tools/build-nav.js [站点根目录,默认本文件的上一级]
作用:扫描站点根目录下的 NN-*.html,采集「章标题(h2)+ 小节(h3)」与
每章的 <meta name="description">,然后重写页面里的占位区块:
章节页:<nav id="chapters"></nav> 侧栏目录树(当前章展开小节)
<p class="chapnav"></p> 「第 N / 17 章」定位条
<nav class="pager"></nav> 上一章 / 下一章
<p class="foot"></p> 页脚
目录页:<nav id="chapters"></nav> 全部章节(不展开小节)
<!-- AUTO:kpis --> 章节 / 小节 / 代码示例 / 字数 四块指标
<!-- AUTO:cards --> 章节卡片(勾选已读 + 展开小节链接)
<nav class="pager"></nav> 「开始阅读」
<p class="foot"></p>
写章节时只写正文,骨架由本脚本统一生成;新增/重排章节后重新执行即可,
幂等、可重复运行。
========================================================================== */
const fs = require("fs");
const path = require("path");
const root = process.argv[2] || path.resolve(__dirname, "..");
const SITE = "Linux 专题";
const SITE_SUB = "从命令行到生产运维的系统知识库";
const esc = s => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const stripTags = s => s.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
const decode = s => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"')
.replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&");
const plain = s => decode(stripTags(s));
/* ---------------------------- 1. 采集 ---------------------------- */
const files = fs.readdirSync(root, { withFileTypes: true })
.filter(e => e.isFile() && /^\d\d-.*\.html$/.test(e.name))
.map(e => e.name).sort();
if (!files.length) {
console.error("没有找到 NN-*.html 章节页,请检查目录:" + root);
process.exit(1);
}
const chapters = files.map(file => {
const html = fs.readFileSync(path.join(root, file), "utf8");
const num = parseInt(file.slice(0, 2), 10);
const h2 = html.match(/<h2 id="[^"]*">([\s\S]*?)<\/h2>/);
if (!h2) throw new Error(`${file}: 找不到 <h2 id="...">章标题</h2>`);
const title = plain(h2[1].replace(/<span class="n">\d+<\/span>/, ""));
const sections = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
.map(m => ({ id: m[1], label: plain(m[2]) }));
const metaDesc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
const metaKeys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
const article = (html.match(/<article>([\s\S]*)<\/article>/) || [, ""])[1];
// 正文字数不含代码块(代码块单独统计段数)
const bodyText = article.replace(/<pre[\s\S]*?<\/pre>/g, " ");
return {
num, file, title, sections,
desc: plain(metaDesc),
keywords: plain(metaKeys),
pres: (html.match(/<pre[\s\S]*?<\/pre>/g) || []).length,
chars: plain(bodyText).replace(/\s+/g, "").length
};
});
const totalSecs = chapters.reduce((n, c) => n + c.sections.length, 0);
const totalPres = chapters.reduce((n, c) => n + c.pres, 0);
const totalChars = chapters.reduce((n, c) => n + c.chars, 0);
/* ---------------------------- 2. 区块生成 ---------------------------- */
function navTree(curNum) {
return chapters.map(c => {
const isCur = c.num === curNum;
const row = isCur
? `<span class="toc-a active" aria-current="page"><i class="cn">${c.num}</i>${esc(c.title)}</span>`
: `<a class="toc-a" href="${c.file}"><i class="cn">${c.num}</i>${esc(c.title)}</a>`;
if (!isCur || !c.sections.length) return row;
const sub = c.sections.map(s =>
`<a class="toc-a lv3" href="#${s.id}">${esc(s.label)}</a>`).join("");
return row + `<div class="subnav current">${sub}</div>`;
}).join("");
}
function chapnav(c) {
return ` <a href="index.html">${SITE}</a>\n` +
` <span>·</span>\n` +
` <span>第 <b class="pos">${c.num}</b> / ${chapters.length} 章</span>`;
}
function pager(c) {
const i = chapters.indexOf(c);
const a = (ch, cls, k) => ch
? ` <a class="${cls}" href="${ch.file}"><span class="k">${k}</span><span class="v">第 ${ch.num} 章 · ${esc(ch.title)}</span></a>`
: ` <a class="${cls} disabled"><span class="k">${k}</span><span class="v">没有更多了</span></a>`;
return a(chapters[i - 1], "prev", "← 上一章") + "\n" + a(chapters[i + 1], "next", "下一章 →");
}
function foot(c) {
return ` ${SITE} · 第 ${c.num} 章 ${esc(c.title)}<br>\n` +
` <a href="index.html">总目录</a> · <a href="../docker/index.html">Docker 专题</a> · ` +
`<a href="../../学习路线/sre-learning-path/index.html">SRE 学习路径</a>`;
}
function kpis() {
const wan = (totalChars / 10000).toFixed(1);
return [
`<div class="kpi"><b>${chapters.length}</b><span>章 · 完整知识体系</span></div>`,
`<div class="kpi"><b>${totalSecs}</b><span>个知识点小节</span></div>`,
`<div class="kpi"><b>${totalPres}</b><span>段可复制代码</span></div>`,
`<div class="kpi"><b>${wan} 万</b><span>字正文</span></div>`
].join("\n ");
}
function cards() {
return chapters.map(c => {
const search = [c.title, c.desc, c.keywords, c.sections.map(s => s.label).join(" ")]
.join(" ").toLowerCase();
const secs = c.sections.map(s =>
`<a href="${c.file}#${s.id}">${esc(s.label)}</a>`).join("");
return ` <div class="chapcard" data-search="${esc(search)}">
<div class="cc-head">
<input type="checkbox" data-ch="${c.num}" aria-label="标记第 ${c.num} 章已读">
<span class="cc-no">${c.num}</span>
<a class="cc-title" href="${c.file}">${esc(c.title)}</a>
<a class="cc-go" href="${c.file}">进入 →</a>
</div>
<p class="cc-desc">${esc(c.desc)}</p>
<details class="cc-secs">
<summary>${c.sections.length} 个小节 · 展开看知识点</summary>
<div>${secs}</div>
</details>
</div>`;
}).join("\n");
}
/* ---------------------------- 3. 写回 ---------------------------- */
const Z = (re, gen, only) => ({ re, gen, only }); // only: "index" | "chapter" | undefined
const zones = [
Z(/<nav id="chapters">[\s\S]*?<\/nav>/, (c, idx) => `<nav id="chapters">${navTree(idx ? 0 : c.num)}</nav>`),
Z(/<p class="chapnav">[\s\S]*?<\/p>/, c => `<p class="chapnav">\n${chapnav(c)}\n </p>`, "chapter"),
Z(/<!-- AUTO:kpis -->[\s\S]*?<!-- \/AUTO:kpis -->/, () => `<!-- AUTO:kpis -->\n ${kpis()}\n <!-- /AUTO:kpis -->`, "index"),
Z(/<!-- AUTO:cards -->[\s\S]*?<!-- \/AUTO:cards -->/, () => `<!-- AUTO:cards -->\n${cards()}\n <!-- /AUTO:cards -->`, "index"),
Z(/<nav class="pager">[\s\S]*?<\/nav>/, (c, idx) => idx
? `<nav class="pager">\n <a class="next" href="${chapters[0].file}"><span class="k">开始阅读 →</span><span class="v">第 1 章 · ${esc(chapters[0].title)}</span></a>\n </nav>`
: `<nav class="pager">\n${pager(c)}\n </nav>`),
Z(/<p class="foot">[\s\S]*?<\/p>/, (c, idx) => idx
? `<p class="foot">\n ${SITE}知识库 · 共 ${chapters.length} 章 ${totalSecs} 个小节 · ${totalPres} 段代码<br>\n <a href="index.html">总目录</a> · <a href="../docker/index.html">Docker 专题</a> · <a href="../../学习路线/sre-learning-path/index.html">SRE 学习路径</a>\n </p>`
: `<p class="foot">\n${foot(c)}\n </p>`)
];
let pages = 0;
const targets = chapters.map(c => ({ c, file: c.file, idx: false }));
if (fs.existsSync(path.join(root, "index.html"))) {
targets.push({ c: chapters[0], file: "index.html", idx: true });
}
for (const t of targets) {
const p = path.join(root, t.file);
let html = fs.readFileSync(p, "utf8");
for (const z of zones) {
if (z.only === "index" && !t.idx) continue;
if (z.only === "chapter" && t.idx) continue;
if (!z.re.test(html)) throw new Error(`${t.file}: 缺少占位区块 ${z.re}`);
html = html.replace(z.re, z.gen(t.c, t.idx));
}
fs.writeFileSync(p, html, "utf8");
pages++;
}
chapters.forEach(c => console.log(
`${c.file.padEnd(20)} 第 ${String(c.num).padStart(2)} 章 · ${String(c.sections.length).padStart(2)} 小节 · ` +
`${String(c.pres).padStart(2)} 段代码 · ${String(c.chars).padStart(6)} 字 · ${c.title}`));
console.log(`\n共 ${chapters.length} 章 / ${totalSecs} 小节 / ${totalPres} 段代码 / ${(totalChars / 10000).toFixed(1)} 万字,已同步 ${pages} 个页面。`);
console.log(`站点副标题:${SITE_SUB}`);