在 Node.js 中使用 Markdown:转换库与工具

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 Node.js 中使用 Markdown:库与工具概览

Markdown 是一种流行的标记语言,用于在文档、博客、README 文件和教育平台中格式化文本。在 Node.js 生态系统中,有多个强大的库可以将 Markdown 转换为 HTML,处理代码、表格和其他元素。在本文中,我们将介绍三种最流行的工具:marked、remarkable 和 showdown,并分析它们的使用示例。



1. marked 库

Marked 是用于解析 Markdown 的最快、最轻量的库之一。它没有外部依赖,并支持 CommonMark 和 GFM(GitHub 风格的 Markdown)。



安装

npm install marked


基本使用

const marked = require('marked');

const markdownString = '# 标题这是**粗体**文本和*斜体*。

- 项目 1- 项目 2';

const html = marked.parse(markdownString);console.log(html);


执行结果:

<h1 id="标题">标题</h1><p>这是 <strong>粗体</strong> 文本和 <em>斜体</em>。</p><ul><li>项目 1</li><li>项目 2</li></ul>


选项配置

Marked 支持多种选项用于精细调整解析:

const marked = require('marked');

marked.setOptions({ breaks: true, // 将换行符转换为 <br> gfm: true, // 支持 GFM headerIds: false // 禁用标题的 id});

const html = marked.parse('第1行第2行');console.log(html);// <p>第1行<br>第2行</p>


2. remarkable 库

Remarkable 是一个灵活的库,支持插件和扩展。它允许接入数学公式、图表和其他特定元素的语法。



安装

npm install remarkable


使用示例

const { Remarkable } = require('remarkable');const md = new Remarkable();

const markdown = '## 子标题

`代码` 和 `行内代码`';const html = md.render(markdown);console.log(html);


输出:

<h2>子标题</h2><p><code>代码</code> 和 <code>行内代码</code></p>


插件与扩展

Remarkable 支持用于处理表格、任务列表和其他元素的插件:

const { Remarkable } = require('remarkable');const md = new Remarkable({  html: true,  linkify: true});

// 添加表格插件md.renderer.rules.table_open = function() { return '<table class="table">';};

const html = md.render('| 列1 | 列2 ||-----------|-----------|| 数据1 | 数据2 |');console.log(html);


3. showdown 库

Showdown 是原始 Showdown 的 JavaScript 移植版本。它易于使用,非常适合客户端-服务器应用程序。



安装

npm install showdown


代码示例

const showdown = require('showdown');const converter = new showdown.Converter();

const markdown = '**粗体** 和 *斜体*';const html = converter.makeHtml(markdown);console.log(html);// <p><strong>粗体</strong> 和 <em>斜体</em></p>


扩展配置

Showdown 支持扩展,可以接入以添加新功能:

const showdown = require('showdown');

// 创建代码高亮扩展const myExt = { type: 'output',

推荐