html-pe
html-pe
is for those who expect accuracy from their HTML parser, but are
unwilling to compromise on performance. This parser handles a variety of edge
cases as prescribed by the HTML5 standard and remains performant thanks to
optimizations such as avoiding regular expressions.
Chunked parsing is supported, and an efficient HTML entity encoder/decoder is included.
Installation
npm install html-pe
Usage
var html = ; var parser = ; // parse chunksparser;parser;parser; // parse entire stringparser;
Optionally, an options
object may be passed to the constructor (default values
shown):
var parser = trim: false // trim whitespace in text nodes decode: true // decode HTML character entities in attribute values and text nodes;
Event Handling
The parser is an EventEmitter
and emits the following events:
// opening tagparser; // text nodeparser; // closing tagparser; // endparser;
Two handlers are provided:
var dom = { // <object> document};dom;// ...dom; var printer = ;printer;
The Printer
handler pretty-prints the parsed HTML to the console. The DOM
handler passes a document
object to its callback, which is detailed below.
Follow the structure in handlers.js
to create new handlers.
DOM Manipulation
The DOM
handler will parse <div id="main">hello <b>world</b></div>
into the
following document
:
type: 'element' parent: {} name: '' attributes: {} children: type: 'element' parent : Circular name: 'div' attributes: id: 'main' children: type: 'text' parent: Circular text: 'hello ' type: 'element' parent: Circular name: 'b' attributes: {} children: type: 'text' parent: Circular text: 'world'
Nodes are either Element
nodes or Text
nodes. All nodes have a textContent
property. Element
nodes provide the DOM navigation methods getElementById
,
getElementsByName
, getElementsByClassName
, and getElementsByTagName
. Two
primitive methods are also available: getElementsBy(test)
and
getElementBy(test)
where test
is a function of type Element -> bool
. For
example, this is how getElementsBy
is used to implement
getElementsByTagName
:
var Element = htmlElement; Elementprototype { return this;}
See dom.js
for details.
HTML Character Entity Encoder/Decoder
var html = ; html;// '<p id="main">Hello &amp; world!</p>'html;// '<p>здравствуйте!</p>' html;// 'It\'s ¬ me'
See encoder.js
for details.
Performance
html-pe
has slightly worse performance than
htmlparser2. A benchmark is available
in tests/bench.js
.
License
MIT. See LICENSE
.