项目推荐:html-to-md - 支持将网页 html 节点转换为 markdown

项目链接地址:
https://github.com/stonehank/html-to-md


一个用于转换HTML为Markdown的工具。

可以获取任意的网页内容转为 markdown 之后保存在自己的仓库


特点

  • 快速,小巧,无任何依赖,gzip 10kb
  • 支持nodeJS,参数(html 文本)为字符串
  • 200+单元测试和模块测试,覆盖率97%

注意:只有有效规范的 HTML 文本才能准确显示结果,如

abc< ,abc等都是无效文本

效果

live-demo: https://stonehank.github.io/html-to-md/


使用说明

安装

npm -i html-to-md

使用

const html2md = require('html-to-md')
// or if you're using ES6
import html2md from 'html-to-md'

console.log(
  html2md('strong and italic', options, force)
)
// ***strong and italic***

参数(可选):

options:

名称

数据类型

默认值

说明

skipTags

Array

[
  'div',
  'html',
  'body',
  'nav',
  'section',
  'footer',
  'main',
  'aside',
  'article',
  'header'
]

需要忽略的标签名

emptyTags

Array

[]

不仅忽略它本身,它内部所有标签名全部忽略

ignoreTags

Array

[
  '',
  'style',
  'head',
  '!doctype',
  'form',
  'svg',
  'noscript',
  'script',
  'meta'
]

忽视标签及其内部所有内容

aliasTags

Object

{
  figure :'p',
  figcaption:'p',
  dl:'p', 
  dd:'p', 
  dt:'p'
}

为标签定义一个别名(通常作用于一些不常用标签)

renderCustomTags

Boolean
| 'SKIP'
| 'EMPTY'
| 'IGNORE'

true

自定义当前标签部分属性配置

tagListener

Function

(props: TagListenerProps): TagListenerReturnProps => props

定义是否渲染自定义标签(非HTML标签),

  • true:渲染
  • false | SKIP:添加至skipTags
  • EMPTY:添加至emptyTags
  • IGNORE:添加至ignoreTags

优先权:skipTags > emptyTags > ignoreTags > aliasTags

例:

html2md('<>abc', { ignoreTags: [''] })
// ''

html2md('<>abc', { skipTags: [''] })
// ***abc***

html2md('<>abc', { emptyTags: [''] })
// abc

html2md('<>abc', {
  skipTags: [''],
  aliasTags: { b: 'ul', i: 'li' },
})
// *  abc

html2md('abc', { renderCustomTags: 'SKIP' })
// ***abc***

force(Boolean)(默认 false)

说明

true

表示强制使用自定义配置

false

对自定义配置使用Object.assign操作

例:

// 默认 skipTags 为 ['div','html','body']

// 配置一:
html2md('
abc
', { skipTags: ['b'] }, false) // skipTags 为 ['div','html','body','b'] // 配置二: html2md('
abc
', { skipTags: ['b'] }, true) // 经过配置后 skipTags 为 ['b']

TagListenerProps

key

说明

parentTag

父标签名,没有则为null

prevTagName

上一个标签名,没有则为null

nextTagName

下一个标签名,没有则为null

isFirstSubTag

是否当前父标签内部的第一个子标签

attrs

当前标签的attributes,以object集合方式,例如 { src, href ... }

innerHTML

内部HTML字符串

match

当前的HTML对应Markdown的匹配符号

language?

当前标签语言,只在 pre 标签中出现

isSelfClosing

是否自闭和标签

TagListenerReturnProps

key

说明

attrs

当前标签的attributes,以object集合方式,例如 { src, href ... }

match

返回一个新的自定义匹配符号

language?

返回自定义pre标签的language

支持标签

  • a
  • b
  • blockquote
  • code
  • del
  • em
  • h1~h6
  • hr
  • i
  • img
  • input
  • li
  • ol
  • p
  • pre
  • s
  • strong
  • table
  • tbody
  • td
  • th
  • thead
  • tr
  • ul