UNPKG

21 kBMarkdownView Raw
1# html-to-text
2
3[![lint status](https://github.com/html-to-text/node-html-to-text/workflows/lint/badge.svg)](https://github.com/html-to-text/node-html-to-text/actions/workflows/lint.yml)
4[![test status](https://github.com/html-to-text/node-html-to-text/workflows/test/badge.svg)](https://github.com/html-to-text/node-html-to-text/actions/workflows/test.yml)
5[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/html-to-text/node-html-to-text/blob/master/LICENSE)
6[![npm](https://img.shields.io/npm/v/html-to-text?logo=npm)](https://www.npmjs.com/package/html-to-text)
7[![npm](https://img.shields.io/npm/dw/html-to-text?color=informational&logo=npm)](https://www.npmjs.com/package/html-to-text)
8
9Advanced converter that parses HTML and returns beautiful text.
10
11## Features
12
13* Inline and block-level tags.
14* Tables with colspans and rowspans.
15* Links with both text and href.
16* Word wrapping.
17* Unicode support.
18* Plenty of customization options.
19
20## Changelog
21
22Available here: [CHANGELOG.md](https://github.com/html-to-text/node-html-to-text/blob/master/packages/html-to-text/CHANGELOG.md)
23
24Version 6 contains a ton of changes, so it worth to take a look at the full changelog.
25
26Version 7 contains an important change for custom formatters.
27
28Version 8 brings the selectors support to greatly increase the flexibility but that also changes some things introduced in version 6. Base element(s) selection also got important changes.
29
30Version 9 drops a lot of previously deprecated options, introduces some new formatters and new capabilities for custom formatters. Now a dual-mode package (cjs and esm). CLI is moved to a [separate package](https://github.com/html-to-text/node-html-to-text/tree/master/packages/html-to-text-cli/).
31
32## Installation
33
34```
35npm install html-to-text
36```
37
38## Usage
39
40Convert a single document:
41
42```js
43const { convert } = require('html-to-text');
44// There is also an alias to `convert` called `htmlToText`.
45
46const html = '<h1>Hello World</h1>';
47const text = convert(html, {
48 wordwrap: 130
49});
50console.log(text); // Hello World
51```
52
53Configure `html-to-text` once for batch processing:
54
55```js
56const { compile } = require('html-to-text');
57
58const convert = compile({
59 wordwrap: 130
60});
61
62const htmls = [
63 '<h1>Hello World!</h1>',
64 '<h1>こんにちは世界!</h1>',
65 '<h1>Привет, мир!</h1>'
66];
67const texts = htmls.map(convert);
68console.log(texts.join('\n'));
69// Hello World!
70// こんにちは世界!
71// Привет, мир!
72```
73
74### Options
75
76#### General options
77
78Option | Default | Description
79----------------------- | ------------ | -----------
80`baseElements` | | Describes which parts of the input document have to be converted and present in the output text, and in what order.
81`baseElements.selectors` | `['body']` | Elements matching any of provided selectors will be processed and included in the output text, with all inner content.<br/>Refer to [Supported selectors](#supported-selectors) section below.
82`baseElements.orderBy` | `'selectors'` | `'selectors'` - arrange base elements in the same order as `baseElements.selectors` array;<br/>`'occurrence'` - arrange base elements in the order they are found in the input document.
83`baseElements.returnDomByDefault` | `true` | Convert the entire document if none of provided selectors match.
84`decodeEntities` | `true` | Decode HTML entities found in the input HTML if `true`. Otherwise preserve in output text.
85`encodeCharacters` | `{}` | A dictionary with characters that should be replaced in the output text and corresponding escape sequences.
86`formatters` | `{}` | An object with custom formatting functions for specific elements (see [Override formatting](#override-formatting) section below).
87`limits` | | Describes how to limit the output text in case of large HTML documents.
88`limits.ellipsis` | `'...'` | A string to insert in place of skipped content.
89`limits.maxBaseElements` | `undefined` | Stop looking for more base elements after reaching this amount. Unlimited if undefined.
90`limits.maxChildNodes` | `undefined` | Maximum number of child nodes of a single node to be added to the output. Unlimited if undefined.
91`limits.maxDepth` | `undefined` | Stop looking for nodes to add to the output below this depth in the DOM tree. Unlimited if undefined.
92`limits.maxInputLength` | `16_777_216` | If the input string is longer than this value - it will be truncated and a message will be sent to `stderr`. Ellipsis is not used in this case. Unlimited if undefined.
93`longWordSplit` | | Describes how to wrap long words.
94`longWordSplit.wrapCharacters` | `[]` | An array containing the characters that may be wrapped on. Checked in order, search stops once line length requirement can be met.
95`longWordSplit.forceWrapOnLimit` | `false` | Break long words at the line length limit in case no better wrap opportunities found.
96`preserveNewlines` | `false` | By default, any newlines `\n` from the input HTML are collapsed into space as any other HTML whitespace characters. If `true`, these newlines will be preserved in the output. This is only useful when input HTML carries some plain text formatting instead of proper tags.
97`selectors` | `[]` | Describes how different HTML elements should be formatted. See [Selectors](#selectors) section below.
98`whitespaceCharacters` | `' \t\r\n\f\u200b'` | A string of characters that are recognized as HTML whitespace. Default value uses the set of characters defined in [HTML4 standard](https://www.w3.org/TR/html4/struct/text.html#h-9.1). (It includes Zero-width space compared to [living standard](https://infra.spec.whatwg.org#ascii-whitespace).)
99`wordwrap` | `80` | After how many chars a line break should follow.<br/>Set to `null` or `false` to disable word-wrapping.
100
101#### Deprecated or removed options
102
103Old&nbsp;option | Depr. | Rem. | Instead&nbsp;use
104-------------------------- | --- | ----- | -----------------
105`baseElement` | 8.0 | | `baseElements: { selectors: [ 'body' ] }`
106`decodeOptions` | | 9.0 | Entity decoding is now handled by [htmlparser2](https://github.com/fb55/htmlparser2) itself and [entities](https://github.com/fb55/entities) internally. No user-configurable parts compared to [he](https://github.com/mathiasbynens/he) besides boolean `decodeEntities`.
107`format` | | 6.0 | The way formatters are written has changed completely. New formatters have to be added to the `formatters` option, old ones can not be reused without rewrite. See [new instructions](#override-formatting) below.
108`hideLinkHrefIfSameAsText` | 6.0 | 9.0 | `selectors: [ { selector: 'a', options: { hideLinkHrefIfSameAsText: true } } ]`
109`ignoreHref` | 6.0 | 9.0 | `selectors: [ { selector: 'a', options: { ignoreHref: true } } ]`
110`ignoreImage` | 6.0 | 9.0 | `selectors: [ { selector: 'img', format: 'skip' } ]`
111`linkHrefBaseUrl` | 6.0 | 9.0 | `selectors: [`<br/>`{ selector: 'a', options: { baseUrl: 'https://example.com' } },`<br/>`{ selector: 'img', options: { baseUrl: 'https://example.com' } }`<br/>`]`
112`noAnchorUrl` | 6.0 | 9.0 | `selectors: [ { selector: 'a', options: { noAnchorUrl: true } } ]`
113`noLinkBrackets` | 6.0 | 9.0 | `selectors: [ { selector: 'a', options: { linkBrackets: false } } ]`
114`returnDomByDefault` | 8.0 | | `baseElements: { returnDomByDefault: true }`
115`singleNewLineParagraphs` | 6.0 | 9.0 | `selectors: [`<br/>`{ selector: 'p', options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },`<br/>`{ selector: 'pre', options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } }`<br/>`]`
116`tables` | 8.0 | | `selectors: [ { selector: 'table.class#id', format: 'dataTable' } ]`
117`tags` | 8.0 | | See [Selectors](#selectors) section below.
118`unorderedListItemPrefix` | 6.0 | 9.0 | `selectors: [ { selector: 'ul', options: { itemPrefix: ' * ' } } ]`
119`uppercaseHeadings` | 6.0 | 9.0 | `selectors: [`<br/>`{ selector: 'h1', options: { uppercase: false } },`<br/>`...`<br/>`{ selector: 'table', options: { uppercaseHeaderCells: false } }`<br/>`]`
120
121Other things removed:
122
123* `fromString` method - use `convert` or `htmlToText` instead;
124* positional arguments in `BlockTextBuilder` methods - pass option objects instead.
125
126#### Selectors
127
128Some example:
129
130```javascript
131const { convert } = require('html-to-text');
132
133const html = '<a href="/page.html">Page</a><a href="!#" class="button">Action</a>';
134const text = convert(html, {
135 selectors: [
136 { selector: 'a', options: { baseUrl: 'https://example.com' } },
137 { selector: 'a.button', format: 'skip' }
138 ]
139});
140console.log(text); // Page [https://example.com/page.html]
141```
142
143Selectors array is our loose approximation of a stylesheet.
144
145* highest [specificity](https://www.w3.org/TR/selectors/#specificity) selector is used when there are multiple matches;
146* the last selector is used when there are multiple matches of equal specificity;
147* all entries with the same selector value are merged (recursively) at the compile stage, in such way so the last defined properties a kept and the relative order of unique selectors is kept;
148* user-defined entries are appended after [predefined entries](#predefined-formatters);
149* Every unique selector must have `format` value specified (at least once);
150* unlike in CSS, values from different matched selectors are NOT merged at the convert stage. Single best match is used instead (that is the last one of those with highest specificity).
151
152To achieve the best performance when checking each DOM element against provided selectors, they are compiled into a decision tree. But it is also important how you choose selectors. For example, `div#id` is much better than `#id` - the former will only check divs for the id while the latter has to check every element in the DOM.
153
154##### Supported selectors
155
156`html-to-text` relies on [parseley](https://github.com/mxxii/parseley) and [selderee](https://github.com/mxxii/selderee) packages for selectors support.
157
158Following selectors can be used in any combinations:
159
160* `*` - universal selector;
161* `div` - tag name;
162* `.foo` - class name;
163* `#bar` - id;
164* `[baz]` - attribute presence;
165* `[baz=buzz]` - attribute value (with any operators and also quotes and case sensitivity modifiers);
166* `+` and `>` combinators (other combinators are not supported).
167
168You can match `<p style="...; display:INLINE; ...">...</p>` with `p[style*="display:inline"i]` for example.
169
170##### Predefined formatters
171
172Following selectors have a formatter specified as a part of the default configuration. Everything can be overridden, but you don't have to repeat the `format` or options that you don't want to override. (But keep in mind this is only true for the same selector. There is no connection between different selectors.)
173
174Selector | Default&nbsp;format | Notes
175------------- | ------------------- | -----
176`*` | `inline` | Universal selector.
177`a` | `anchor` |
178`article` | `block` |
179`aside` | `block` |
180`blockquote` | `blockquote` |
181`br` | `lineBreak` |
182`div` | `block` |
183`footer` | `block` |
184`form` | `block` |
185`h1` | `heading` |
186`h2` | `heading` |
187`h3` | `heading` |
188`h4` | `heading` |
189`h5` | `heading` |
190`h6` | `heading` |
191`header` | `block` |
192`hr` | `horizontalLine` |
193`img` | `image` |
194`main` | `block` |
195`nav` | `block` |
196`ol` | `orderedList` |
197`p` | `paragraph` |
198`pre` | `pre` |
199`table` | `table` | Equivalent to `block`. Use `dataTable` instead for tabular data.
200`ul` | `unorderedList` |
201`wbr` | `wbr` |
202
203More formatters also available for use:
204
205Format | Description
206---------------- | -----------
207`dataTable` | For visually-accurate tables. Note that this might be not search-friendly (output text will look like gibberish to a machine when there is any wrapped cell contents) and also better to be avoided for tables used as a page layout tool.
208`skip` | Skips the given tag with it's contents without printing anything.
209`blockString` | Insert a block with the given string literal (`formatOptions.string`) instead of the tag.
210`blockTag` | Render an element as HTML block bag, convert it's contents to text.
211`blockHtml` | Render an element with all it's children as HTML block.
212`inlineString` | Insert the given string literal (`formatOptions.string`) inline instead of the tag.
213`inlineSurround` | Render inline element wrapped with given strings (`formatOptions.prefix` and `formatOptions.suffix`).
214`inlineTag` | Render an element as inline HTML tag, convert it's contents to text.
215`inlineHtml` | Render an element with all it's children as inline HTML.
216
217##### Format options
218
219Following options are available for built-in formatters.
220
221Option | Default | Applies&nbsp;to | Description
222------------------- | ----------- | ------------------ | -----------
223`leadingLineBreaks` | `1`, `2` or `3` | all block-level formatters | Number of line breaks to separate previous block from this one.<br/>Note that N+1 line breaks are needed to make N empty lines.
224`trailingLineBreaks` | `1` or `2` | all block-level formatters | Number of line breaks to separate this block from the next one.<br/>Note that N+1 line breaks are needed to make N empty lines.
225`baseUrl` | `null` | `anchor`, `image` | Server host for link `href` attributes and image `src` attributes relative to the root (the ones that start with `/`).<br/>For example, with `baseUrl = 'http://asdf.com'` and `<a href='/dir/subdir'>...</a>` the link in the text will be `http://asdf.com/dir/subdir`.
226`linkBrackets` | `['[', ']']` | `anchor`, `image` | Surround links with these brackets.<br/>Set to `false` or `['', '']` to disable.
227`pathRewrite` | `undefined` | `anchor`, `image` | A function to rewrite link `href` attributes and image `src` attributes. Optional second argument is the metadata object.<br/>Applied before `baseUrl`.
228`hideLinkHrefIfSameAsText` | `false` | `anchor` | By default links are translated in the following way:<br/>`<a href='link'>text</a>` => becomes => `text [link]`.<br/>If this option is set to `true` and `link` and `text` are the same, `[link]` will be omitted and only `text` will be present.
229`ignoreHref` | `false` | `anchor` | Ignore all links. Only process internal text of anchor tags.
230`noAnchorUrl` | `true` | `anchor` | Ignore anchor links (where `href='#...'`).
231`itemPrefix` | `' * '` | `unorderedList` | String prefix for each list item.
232`uppercase` | `true` | `heading` | By default, headings (`<h1>`, `<h2>`, etc) are uppercased.<br/>Set this to `false` to leave headings as they are.
233`length` | `undefined` | `horizontalLine` | Length of the line. If undefined then `wordwrap` value is used. Falls back to 40 if that's also disabled.
234`trimEmptyLines` | `true` | `blockquote` | Trim empty lines from blockquote.<br/>While empty lines should be preserved in HTML, space-saving behavior is chosen as default for convenience.
235`uppercaseHeaderCells` | `true` | `dataTable` | By default, heading cells (`<th>`) are uppercased.<br/>Set this to `false` to leave heading cells as they are.
236`maxColumnWidth` | `60` | `dataTable` | Data table cell content will be wrapped to fit this width instead of global `wordwrap` limit.<br/>Set this to `undefined` in order to fall back to `wordwrap` limit.
237`colSpacing` | `3` | `dataTable` | Number of spaces between data table columns.
238`rowSpacing` | `0` | `dataTable` | Number of empty lines between data table rows.
239`string` | `''` | `blockString`, `inlineString` | A string to be inserted in place of a tag.
240`prefix` | `''` | `inlineSurround` | String prefix to be inserted before inline tag contents.
241`suffix` | `''` | `inlineSurround` | String suffix to be inserted after inline tag contents.
242
243##### Deprecated format options
244
245Old option | Applies&nbsp;to | Depr. | Rem. | Instead use
246------------------- | ------------------ | ----- | ---- | ---------------------
247`noLinkBrackets` | `anchor` | 8.1 | | `linkBrackets: false`
248
249### Override formatting
250
251`formatters` option is an object that holds formatting functions. They can be assigned to format different elements in the `selectors` array.
252
253Each formatter is a function of four arguments that returns nothing. Arguments are:
254
255* `elem` - the HTML element to be processed by this formatter;
256* `walk` - recursive function to process the children of this element. Called as `walk(elem.children, builder)`;
257* `builder` - [BlockTextBuilder](https://github.com/html-to-text/node-html-to-text/blob/master/packages/base/src/block-text-builder.js) object. Manipulate this object state to build the output text;
258* `formatOptions` - options that are specified for a tag, along with this formatter (Note: if you need general html-to-text [options](#general-options) - they are accessible via `builder.options`).
259
260Custom formatter example:
261
262```javascript
263const { convert } = require('html-to-text');
264
265const html = '<foo>Hello World</foo>';
266const text = convert(html, {
267 formatters: {
268 // Create a formatter.
269 'fooBlockFormatter': function (elem, walk, builder, formatOptions) {
270 builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 1 });
271 walk(elem.children, builder);
272 builder.addInline('!');
273 builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 1 });
274 }
275 },
276 selectors: [
277 // Assign it to `foo` tags.
278 {
279 selector: 'foo',
280 format: 'fooBlockFormatter',
281 options: { leadingLineBreaks: 1, trailingLineBreaks: 1 }
282 }
283 ]
284});
285console.log(text); // Hello World!
286```
287
288New in version 9: metadata object can be provided as the last optional argument of the `convert` function (or the function returned by `compile` function). It can be accessed by formatters as `builder.metadata`.
289
290Refer to [generic formatters](https://github.com/html-to-text/node-html-to-text/blob/master/packages/base/src/generic-formatters.js) of the base package and [text formatters](https://github.com/html-to-text/node-html-to-text/blob/master/packages/html-to-text/src/text-formatters.js) of this package for more examples. The easiest way to write your own is to pick an existing one and customize.
291
292Refer to [BlockTextBuilder](https://github.com/html-to-text/node-html-to-text/blob/master/packages/base/src/block-text-builder.js) for available functions and arguments.
293
294#### Call other formatters from a custom formatter
295
296Most of the times this is *not* what you actually need. Most practical problems can be solved with [selectors](#selectors).
297
298If you really need to inspect the node internals, not just attributes, then you can do it like this:
299
300```javascript
301const options = {
302 // ...
303 formatters: {
304 filterBlockFormatter: function (elem, walk, builder, formatOptions) {
305 // all built-in and custom formatters available by name
306 const blockFormatter = builder.options.formatters['block'];
307 if (blockFormatter && elem.children.some(/* predicate */)) {
308 blockFormatter(elem, walk, builder, formatOptions);
309 }
310 }
311 },
312 selectors: [
313 {
314 selector: 'div.questionable',
315 format: 'filterBlockFormatter',
316 options: { leadingLineBreaks: 1, trailingLineBreaks: 1 }
317 }
318 ],
319 // ...
320}
321```
322
323## Example
324
325* Input text: [test.html](https://github.com/html-to-text/node-html-to-text/blob/master/packages/html-to-text/test/test.html)
326* Output text: [test.txt](https://github.com/html-to-text/node-html-to-text/blob/master/packages/html-to-text/test/test.txt)
327
328## Contributors
329
330* [@mlegenhausen](https://github.com/mlegenhausen) - creator;
331* [@KillyMXI](https://github.com/KillyMXI) - maintainer since 2020;
332* Everyone else who [added something](https://github.com/html-to-text/node-html-to-text/graphs/contributors) to the tool or helped us shaping it via [issues](https://github.com/html-to-text/node-html-to-text/issues) and [PRs](https://github.com/html-to-text/node-html-to-text/pulls).
333
334## License
335
336[MIT License](https://github.com/html-to-text/node-html-to-text/blob/master/LICENSE)