html-to-text 是一款开源库,可将 HTML 转为结构清晰的纯文本,支持自动换行、Unicode、多种渲染选项和自定义钩子,适用于邮件渲染、日志输出、爬虫抓取等场景。

安装

npm install html-to-text

核心功能

  • 标签处理:智能区分内联(如 <span>)和块级(如 <p>)元素,添加空格与换行。

  • 表格:可渲染为 Markdown 或模拟文本表格。

  • 链接与图片:保留链接文本(可附带 URL)或忽略;图片占位或跳过。

  • 美化选项:自定义列宽、Unicode 支持、标签映射(如将 <h1> 渲染为 # )。

基本用法

const { convert } = require('html-to-text');
const text = convert(html, { wordwrap: 50, tables: true });
console.log(text);

示例输出:

# 示例标题

这是一个 **加粗** 的段落,包含 链接 (https://example.com)。

| 列1 | 列2 |
| --- | --- |
| 数据A | 数据B |

忽略链接和图片

const { convert } = require('html-to-text');

const text = convert(html, {
  wordwrap: false,
  ignoreImage: true,
  ignoreHref: true
});

输出:

Welcome to My Website
This is a paragraph with a .
Another paragraph.