Socket
Socket
Sign inDemoInstall

html-to-text

Package Overview
Dependencies
5
Maintainers
2
Versions
55
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    html-to-text

Advanced html to plain text converter


Version published
Weekly downloads
1.8M
increased by7.75%
Maintainers
2
Install size
1.92 MB
Created
Weekly downloads
 

Package description

What is html-to-text?

The html-to-text npm package is designed to convert HTML documents into plain text. It can handle various HTML elements, preserving the basic structure and formatting in a text-only format. This is particularly useful for extracting text from HTML emails, web pages, or any HTML content for use in text-based formats.

What are html-to-text's main functionalities?

Convert HTML to plain text

This feature allows you to convert a string of HTML into a plain text format, with options such as word wrapping.

const htmlToText = require('html-to-text');
const html = '<h1>Hello World</h1>';
const text = htmlToText.fromString(html, {
  wordwrap: 130
});
console.log(text); // Outputs: 'Hello World'

Handling of tables

This feature enables the conversion of HTML tables into a tabular text format, preserving the layout of the data.

const htmlToText = require('html-to-text');
const html = '<table><tr><td>Foo</td><td>Bar</td></tr></table>';
const text = htmlToText.fromString(html, {
  tables: true
});
console.log(text); // Outputs a text representation of the table

Handling of lists

This feature converts HTML lists into plain text, with customizable prefixes for list items.

const htmlToText = require('html-to-text');
const html = '<ul><li>Item 1</li><li>Item 2</li></ul>';
const text = htmlToText.fromString(html, {
  unorderedListItemPrefix: '- '
});
console.log(text); // Outputs: '- Item 1\n- Item 2'

Handling of hyperlinks

This feature allows for the conversion of hyperlinks into plain text, with options to hide or display the URL based on the link text.

const htmlToText = require('html-to-text');
const html = '<a href='https://example.com'>Example</a>';
const text = htmlToText.fromString(html, {
  hideLinkHrefIfSameAsText: true
});
console.log(text); // Outputs: 'Example'

Other packages similar to html-to-text

Readme

Source

html-to-text

Build Status Test Coverage License: MIT npm npm

Advanced converter that parses HTML and returns beautiful text.

Features

  • Inline and block-level tags.
  • Tables with colspans and rowspans.
  • Links with both text and href.
  • Word wrapping.
  • Unicode support.
  • Plenty of customization options.

Changelog

Available here: CHANGELOG.md

Version 6 contains a ton of changes, so it worth to take a look.

Installation

npm install html-to-text

Or when you want to use it as command line interface it is recommended to install it globally via

npm install html-to-text -g

Usage

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

const text = htmlToText('<h1>Hello World</h1>', {
  wordwrap: 130
});
console.log(text); // Hello World

Options

General options
OptionDefaultDescription
baseElement'body'The tag(s) whose text content will be captured from the html and added to the resulting text output.
Single element or an array of elements can be specified, each as a single tag name with optional css class and id parameters e.g. ['p.class1.class2#id1#id2', 'p.class1.class2#id1#id2'].
decodeOptions{ isAttributeValue: false, strict: false }Text decoding options given to he.decode. For more informations see the he module.
formatters{}An object with custom formatting functions for specific elements (see "Override formatting" section below).
limitsDescribes how to limit the output text in case of large HTML documents.
limits.ellipsis'...'A string to insert in place of skipped content.
limits.maxChildNodesundefinedMaximum number of child nodes of a single node to be added to the output. Unlimited if undefined.
limits.maxDepthundefinedStop looking for nodes to add to the output below this depth in the DOM tree. Unlimited if undefined.
limits.maxInputLength16_777_216If 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.
longWordSplitDescribes how to wrap long words.
longWordSplit.wrapCharacters[]An array containing the characters that may be wrapped on. Checked in order, search stops once line length requirement can be met.
longWordSplit.forceWrapOnLimitfalseBreak long words at the line length limit in case no better wrap opportunities found.
preserveNewlinesfalseBy default, any newlines \n in a block of text will be removed. If true, these newlines will not be removed.
returnDomByDefaulttrueConvert the entire document if we don't find the tag defined in baseElement.
tables[]Allows to select certain tables by the class or id attribute from the HTML document. This is necessary because the majority of HTML E-Mails uses a table based layout. Prefix your table selectors with an . for the class and with a # for the id attribute. All other tables are ignored.
You can assign true to this attribute to select all tables.
tagsDescribes how different tags should be formatted. See "Tags" section below.
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. (It includes Zero-width space compared to living standard.)
wordwrap80After how many chars a line break should follow.
Set to null or false to disable word-wrapping.
Options deprecated in version 6
Old optionInstead use
hideLinkHrefIfSameAsTexthideLinkHrefIfSameAsText option for tags with anchor formatter.
ignoreHrefignoreHref option for tags with anchor formatter.
ignoreImageSet format to skip for img tags.
linkHrefBaseUrlbaseUrl option for tags with anchor and image formatters.
noAnchorUrlnoAnchorUrl option for tags with anchor formatter.
noLinkBracketsnoLinkBrackets option for tags with anchor formatter.
singleNewLineParagraphsSet leadingLineBreaks and trailingLineBreaks options to 1 for p and pre tags.
unorderedListItemPrefixitemPrefix option for tags with unorderedList formatter.
uppercaseHeadingsuppercase option for tags with heading formatter, uppercaseHeaderCells option for table or dataTable formatters.

Deprecated options will be removed with future major version update.

Options removed in version 6
Old optionDescription
formatThe 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 below.
Tags

By default there are following tag to formatter assignments:

Tag nameDefault formatNotes
''inlineCatch-all default for unknown tags.
aanchor
articleblock
asideblock
blockquoteblockquote
brlineBreak
divblock
footerblock
formblock
h1heading
h2heading
h3heading
h4heading
h5heading
h6heading
headerblock
hrhorizontalLine
imgimage
mainblock
navblock
olorderedList
pparagraph
prepre
tabletablethere is also dataTable formatter. Using it will be equivalent to setting tables to true. tables option might be deprecated in the future.
ulunorderedList
wbrwbr

More formatters also available for use:

  • skip - as the name implies it skips the given tag with it's contents without printing anything.

Format options are specified for each tag indepentently:

OptionDefaultApplies toDescription
leadingLineBreaks1, 2 or 3all block-level formattersNumber of line breaks to separate previous block from this one.
Note that N+1 line breaks are needed to make N empty lines.
trailingLineBreaks1 or 2all block-level formattersNumber of line breaks to separate this block from the next one.
Note that N+1 line breaks are needed to make N empty lines.
baseUrlnullanchor, imageServer host for link href attributes and image src attributes relative to the root (the ones that start with /).
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.
Keep in mind that baseUrl should not end with a /.
hideLinkHrefIfSameAsTextfalseanchorBy default links are translated in the following way:
<a href='link'>text</a> => becomes => text [link].
If this option is set to true and link and text are the same, [link] will be omitted and only text will be present.
ignoreHreffalseanchorIgnore all links. Only process internal text of anchor tags.
noAnchorUrltrueanchorIgnore anchor links (where href='#...').
noLinkBracketsfalseanchorDon't print brackets around links.
itemPrefix' * 'unorderedListString prefix for each list item.
uppercasetrueheadingBy default, headings (<h1>, <h2>, etc) are uppercased.
Set this to false to leave headings as they are.
lengthundefinedhorizontalLineLength of the line. If undefined then wordwrap value is used. Falls back to 40 if that's also disabled.
trimEmptyLinestrueblockquoteTrim empty lines from blockquote.
While empty lines should be preserved in HTML, space-saving behavior is chosen as default for convenience.
uppercaseHeaderCellstruetable, dataTableBy default, heading cells (<th>) are uppercased.
Set this to false to leave heading cells as they are.
maxColumnWidth60table, dataTableData table cell content will be wrapped to fit this width instead of global wordwrap limit.
Set to undefined in order to fall back to wordwrap limit.
colSpacing3table, dataTableNumber of spaces between data table columns.
rowSpacing0table, dataTableNumber of empty lines between data table rows.

How to set a specific format option, example:

var { htmlToText } = require('html-to-text');

var text = htmlToText('<a href="/page.html">Page</a>', {
  tags: { 'a': { options: { baseUrl: 'https://example.com' } } }
});

console.log(text); // Page [https://example.com/page.html]

Override formatting

This is significantly changed in version 6.

formatters option is an object that holds formatting functions. They can be assigned to format different tags by key in the tags option.

Each formatter is a function of four arguments that returns nothing. Arguments are:

  • elem - the HTML element to be processed by this formatter;
  • walk - recursive function to process the children of this element. Called as walk(elem.children, builder);
  • builder - BlockTextBuilder object. Manipulate this object state to build the output text;
  • formatOptions - options that are specified for a tag, along with this formatter (Note: if you need global html-to-text options - they are accessible via builder.options).

Custom formatter example:

var { htmlToText } = require('html-to-text');

var text = htmlToText('<foo>Hello World</foo>', {
  formatters: {
    // Create a formatter.
    'fooBlockFormatter': function (elem, walk, builder, formatOptions) {
      builder.openBlock(formatOptions.leadingLineBreaks || 1);
      walk(elem.children, builder);
      builder.addInline('!');
      builder.closeBlock(formatOptions.trailingLineBreaks || 1);
    }
  },
  tags: {
    // Assign it to `foo` tags.
    'foo': {
      format: 'fooBlockFormatter',
      options: { leadingLineBreaks: 1, trailingLineBreaks: 1 }
    }
  }
});

console.log(text); // Hello World!

Refer to built-in formatters for more examples.

Refer to BlockTextBuilder for available functions and arguments.

Command Line Interface

It is possible to use html-to-text as command line interface. This allows an easy validation of your generated text and the integration in other systems that does not run on node.js.

html-to-text uses stdin and stdout for data in and output. So you can use html-to-text the following way:

cat example/test.html | html-to-text > test.txt

There also all options available as described above. You can use them like this:

cat example/test.html | html-to-text --tables=#invoice,.address --wordwrap=100 > test.txt

The tables option has to be declared as comma separated list without whitespaces.

Example

Contributors

License

MIT License

Keywords

FAQs

Last updated on 31 Oct 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc