NodeJS中html转markdown

turndown 库

javascript 复制代码
const TurndownService = require('turndown');
const turndownService = new TurndownService();

const htmlContent = '<h1>Hello, World!</h1><p>This is a <em>paragraph</em>.</p>';
const markdownContent = turndownService.turndown(htmlContent);

console.log(markdownContent);

用 Turndown 的 addRule 方法添加自定义规则

javascript 复制代码
const TurndownService = require("turndown");
const turndownService = new TurndownService();
// 添加处理标题的规则
turndownService.addRule("heading", {
	filter: ["h1", "h2", "h3", "h4", "h5", "h6"],
	replacement: function (content, node, options) {
		var hLevel = Number(node.nodeName.charAt(1));
		return Array(hLevel + 1).join("#") + " " + content + "\n";
	},
});
// 添加处理代码块的规则
turndownService.addRule('code', {
    filter: function (node) {
      return (node.tagName === 'PRE' && node.firstChild && node.firstChild.tagName === 'CODE' && node.firstChild.className);
    },
    replacement: function (content, node, options) {
      var lang = node.firstChild.className.match(/language-(\w+)/);
      if (lang) {
        return '\n```' + lang[1] + '\n' + node.firstChild.textContent + '\n```\n';
      }
      return '\n```\n' + node.firstChild.textContent + '\n```\n';
    }
  });

让 Turndown 识别 <code> 标签中的类名,比如 <pre><code class="prism language-js"> )并根据类名来确定代码块的语言,你可以在处理代码块的规则中进行相应的修改。

相关推荐
JIngJaneIL18 分钟前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码25 分钟前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
澄江静如练_35 分钟前
列表渲染(v-for)
前端·javascript·vue.js
JustHappy1 小时前
「chrome extensions🛠️」我写了一个超级简单的浏览器插件Vue开发模板
前端·javascript·github
Loo国昌1 小时前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构
sg_knight1 小时前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
LYFlied1 小时前
【每日算法】LeetCode 17. 电话号码的字母组合
前端·算法·leetcode·面试·职场和发展
开发者小天1 小时前
react中useEffect的用法,以及订阅模式的原理
前端·react.js·前端框架
前端白袍2 小时前
Vue:如何实现一个具有复制功能的文字按钮?
前端·javascript·vue.js