nodejs md文件转html

javascript 复制代码
const marked = require('marked');

// 要转换的 Markdown 文本
const markdownText = `
# Hello, Markdown!

This is a paragraph.

- List item 1
- List item 2
`;

// 使用 marked 将 Markdown 转换为 HTML
const html = marked(markdownText);

console.log(html);

我直接读取md文件转换结果有误,第1行本应是标题1却变成了段落。文件内容跟上面字符串完全一样。后来打印二进制才知道从文件读取的前面多了些东西,原因是文件用了UTF8 BOM编码,最后改成UTF8编码问题解决。

javascript 复制代码
markdownContent = fs.readFileSync('.test.md', 'utf8');
const encoder = new TextEncoder();
console.log(encoder.encode(markdownContent));

marked用法

覆盖默认的渲染函数
javascript 复制代码
const marked = require('marked');

// 覆盖默认的渲染函数
const renderer = {
  // 处理标题的渲染函数,text 是标题文本,depth 是标题级别
  heading(text, depth) {
    // 将文本转换为小写,并将非单词字符替换为连字符 -
    const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');

    // 返回生成的 HTML 代码片段,包含锚点和标题文本
    return `
      <h${depth}>
        <a name="${escapedText}" class="anchor" href="#${escapedText}">
          <span class="header-link"></span>
        </a>
        ${text}
      </h${depth}>`;
  },
  code(raw, lang) {
    return `<pre><code class="prism language-${lang}">${raw}</code></pre>`;
}
};

// 将自定义的渲染函数应用于 marked 模块
marked.use({ renderer });

// 解析并输出 Markdown 文本
console.log(marked.parse('# heading+'));
const markdownText = `
\`\`\`python
print("Hello, World!")
\`\`\`
`;
console.log(marked.parse(markdownText));

官方资料:

https://marked.js.org/using_pro

相关推荐
TechWayfarer20 小时前
PHP漏洞被利用,怎么揪出攻击IP?
开发语言·python·tcp/ip·网络安全·php
卡卡~~21 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
qq_4069810321 小时前
大白话rust系列09 函数调用两次有什么错?
开发语言·python·rust
学逆向的1 天前
C 多文件开发
c语言·开发语言·网络安全
布吉岛的石头1 天前
Java 程序员第 50 阶段3:数据工程:预训练语料清洗与去重
java·开发语言·人工智能·深度学习·transformer
benchmark_cc1 天前
QuantDash 安装成功后,如何验证 Python 环境可以正常导入 SDK?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
学逆向的1 天前
C 内存属性
c语言·开发语言·算法·网络安全
HAPPY酷1 天前
C++ 自定义内存池优化点云处理:从裸指针到 RAII 自动回收
开发语言·c++
梦帮科技1 天前
量子纠缠网络与量子隐形传态攻防:量子中继器信道串扰、纠缠态保真度降解与量子路由劫持
开发语言·网络·人工智能·算法·自动化·php