1 Star 35 Fork 15

linwu-hi/coding-time-chrome

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
generateTableOfContents.js 1.29 KB
一键复制 编辑 原始数据 按行查看 历史
linwu-hi 提交于 2023-06-22 18:35 +08:00 . feat: 添加《谷歌插件开发小册》📚
const fs = require('fs');
const markdownIt = require('markdown-it');
const markdownItAnchor = require('markdown-it-anchor');
// 扫描 Markdown 文件并生成目录
function generateTableOfContents(filePath) {
// 读取 Markdown 文件内容
const markdown = fs.readFileSync(filePath, 'utf8');
// 创建 Markdown 解析器实例,并添加 markdown-it-anchor 插件
const md = markdownIt().use(markdownItAnchor);
// 解析 Markdown 文件内容
const tokens = md.parse(markdown, {});
// 存储目录项的数组
const toc = [];
// 遍历解析后的 tokens
for (const token of tokens) {
if (token.type === 'heading_open' && token.tag.startsWith('h')) {
// 提取标题级别、标题文本和锚点链接
const level = parseInt(token.tag.slice(1));
const text = tokens[tokens.indexOf(token) + 1].content;
const anchorLink = tokens[tokens.indexOf(token)].attrs.find(attr => attr[0] === 'id')[1];
// 将目录项添加到数组
toc.push({ level, text, anchorLink });
}
}
// 打印目录
for (const item of toc) {
console.log(`${' '.repeat(item.level - 1)}- [${item.text}](#${item.anchorLink})`);
}
}
// 指定要扫描的 Markdown 文件路径
const filePath = './README.md';
// 调用方法生成目录
generateTableOfContents(filePath);
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/linwu-hi/coding-time-chrome.git
git@gitee.com:linwu-hi/coding-time-chrome.git
linwu-hi
coding-time-chrome
coding-time-chrome
main

搜索帮助