#!/usr/bin/env node /* ========================================================================== 模块目录页生成器(全部阶段) 用法:node tools/build-module-index.js [站点根目录,默认本文件的上一级] 作用:读取 tools/modules-plan.json 里的模块级元数据(标题 / 副标题 / 导语 / 建议投入),再扫描 modules//NN-*.html 解析出每章的 h2 标题与全部 h3 小节, 生成模块目录页 modules//index.html。 为什么章节标题不写在 plan 里:目录页与正文必须永远一致。从正文解析, 就不会出现「改了正文章节标题、目录页还是旧的」这类问题。 跳过规则:plan 里列了、但目录不存在或没有 NN-*.html 的模块视为「筹备中」, 照样参与编号与前后模块关系(上一/下一模块会指向它,并标注「筹备中」)。 这样阶段与模块的编号永远和 index.html 的 STAGES 对齐,不会因为先写哪个模块而错位。 上一 / 下一模块按「全书展平顺序」计算,跨阶段也连续: 阶段 0 最后一个模块 → 阶段 1 第一个模块。 幂等:可重复运行;生成后建议再跑一次 tools/build-nav.js 同步侧栏目录树。 ========================================================================== */ const fs = require("fs"); const path = require("path"); const root = process.argv[2] || path.resolve(__dirname, ".."); const MODDIR = path.join(root, "modules"); const PLAN = path.join(__dirname, "modules-plan.json"); /* ---------- 读取 JSONC(允许 /* *​/ 注释) ---------- */ function readPlan(p) { const raw = fs.readFileSync(p, "utf8") .replace(/\/\*[\s\S]*?\*\//g, "") .replace(/^\s*\/\/.*$/gm, ""); return JSON.parse(raw); } const esc = s => String(s).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); const stripTags = s => s.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim(); const decode = s => s.replace(/</g, "<").replace(/>/g, ">") .replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, " ").replace(/&/g, "&"); const plain = s => decode(stripTags(s)); const stripNo = s => s.replace(/^\s*\d+(?:\.\d+)*\s*[\.、]?\s*/, "").trim(); const plan = readPlan(PLAN); const stages = plan.stages; const brand = plan.brand; /* ---------- 1. 扫描:每个模块能否生成 ---------- */ const slots = []; // 全展平,顺序 = 阶段顺序 + 模块下标顺序 stages.forEach((st, si) => { if (!st.modules) st.modules = []; st.modules.forEach((m, mi) => { const modPath = path.join(MODDIR, m.dir); const files = fs.existsSync(modPath) ? fs.readdirSync(modPath).filter(f => /^\d\d-.*\.html$/.test(f)).sort() : []; let chapters = null; if (files.length) { chapters = files.map(file => { const html = fs.readFileSync(path.join(modPath, file), "utf8"); const h2 = html.match(/

([\s\S]*?)<\/h2>/); if (!h2) throw new Error(`modules/${m.dir}/${file}: 找不到 h2 章节标题`); const title = plain(h2[1].replace(/\d+<\/span>/, "")); const sections = [...html.matchAll(/

([\s\S]*?)<\/h3>/g)] .map(x => ({ id: x[1], label: stripNo(plain(x[2])) })); // 字数口径:只统计中文汉字(代码与英文命令不计入「千字」,否则会被严重高估) const chars = (stripTags(html).match(/[\u4e00-\u9fff]/g) || []).length; return { file, title, sections, chars }; }); } slots.push({ st, si, m, mi, modPath, chapters, files }); }); }); const built = slots.filter(s => s.chapters); const report = []; let written = 0; /* ---------- 2. 逐模块生成 ---------- */ built.forEach((slot, gi) => { const { st, m, mi, modPath, chapters } = slot; const prevSlot = gi > 0 ? built[gi - 1] : null; const nextSlot = gi < built.length - 1 ? built[gi + 1] : null; // 本阶段的下一个模块(可能还没写) const nextInStage = nextSlot && nextSlot.st === st ? nextSlot : slots.find(s => s.st === st && s.mi === mi + 1) || null; const chapItems = chapters.map((c, i) => { const secs = c.sections.length ? `\n
${c.sections.map(s => `${esc(s.label)}`).join("")}
` : ""; return `
  • ${secs}
  • `; }).join("\n"); const totalSecs = chapters.reduce((n, c) => n + c.sections.length, 0); const totalK = Math.round(chapters.reduce((n, c) => n + c.chars, 0) / 1000); const prev = prevSlot ? { href: `../${prevSlot.m.dir}/index.html`, k: "← 上一模块", v: prevSlot.m.title } : { href: `${brand.home}#${st.id}`, k: "← 上一模块", v: `本阶段(${st.anchorText})的第一个模块` }; let next; if (nextSlot) { next = { href: `../${nextSlot.m.dir}/index.html`, k: nextSlot.st === st ? "下一模块 →" : `${nextSlot.st.anchorText} →`, v: nextSlot.m.title }; } else if (nextInStage) { next = { href: `${brand.home}#${st.id}`, k: "下一模块 →", v: `筹备中:${nextInStage.m.title}` }; } else if (stages[slot.si + 1]) { const nx = stages[slot.si + 1]; next = { href: `${brand.home}#${nx.id}`, k: `${nx.anchorText} →`, v: `回到学习路径,进入${nx.anchorText}` }; } else { next = { href: `${brand.home}#${st.id}`, k: "学习路径 →", v: "回到学习路径" }; } const html = ` ${esc(m.title)} · ${st.anchorText} 模块 ${mi + 1} · ${esc(brand.siteName)}
    ${esc(st.anchorText)} · 模块 ${mi + 1} / ${st.modules.length}

    ${esc(m.title)}

    ${esc(m.sub)}

    共 ${chapters.length} 章 ${totalSecs} 个小节 约 ${totalK} 千字 ${esc(m.hours)}

    ${m.lead}

    章节目录

      ${chapItems}
    怎么用这一模块

    左侧第一栏是章节,可以在整章之间跳转;第二栏是本章小节,进入某章后会显示该章的内容大纲并跟随滚动高亮。

    每章结尾都可以用底部的「上一章 / 下一章」连续阅读。每章内部的代码块右上角可以直接复制,点顶栏的「深色 / 浅色」可以切换主题。

    ${esc(m.title)} · 模块目录
    返回学习路径

    `; fs.writeFileSync(path.join(modPath, "index.html"), html, "utf8"); written++; report.push(`modules/${m.dir}/index.html:${chapters.length} 章 / ${totalSecs} 小节 / 约 ${totalK} 千字`); }); const pending = slots.filter(s => !s.chapters); pending.forEach(s => report.push(`modules/${s.m.dir}/(筹备中,跳过):${s.st.anchorText} 模块 ${s.mi + 1} ${s.m.title}`)); console.log(report.join("\n")); console.log(`\n共生成 ${written} 个模块目录页(筹备中跳过 ${pending.length} 个)。下一步:node tools/build-nav.js`);