#!/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])) })); // 字数口径:只统计中文汉字(代码与英文命令不计入「千字」,否则会被严重高估); // 侧栏目录树(build-nav.js 写入的整本书目录)与代码块(含中文注释)都不属于正文,先剥掉再数 const prose = html .replace(//g, "") .replace(/