Registry / serialization / htmlparser2

htmlparser2

JSON →
library12.0.0jsnpmunverified

htmlparser2 is a high-performance, event-driven HTML/XML parser for JavaScript and TypeScript environments. It is currently at stable version 12.0.0 and maintains an active release cadence with frequent updates, often aligning with WHATWG specifications. The library prioritizes speed and efficiency, making it suitable for tasks like web scraping, content transformation, and processing RSS/Atom feeds. While fast and forgiving, it takes some shortcuts compared to strictly spec-compliant parsers like `parse5`, which might lead to different parsing results for highly malformed HTML. It integrates with an ecosystem of related packages like `domhandler` for DOM construction and `css-select` for querying.

npm install htmlparser2
INSTALL
IMPORT
SIG · HTMLPARSER2
H
htmlparser2
serializationjavascriptv12.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Parser
import { Parser } from 'htmlparser2';
const Parser = require('htmlparser2').Parser;
Since v11.0.0, htmlparser2 is an ESM-only module. CommonJS `require()` is no longer supported.
parseDocument
import { parseDocument } from 'htmlparser2';
const parseDocument = require('htmlparser2').parseDocument;
A convenience function for parsing a document and returning a DOM structure using `domhandler`.
WebWritableStream
import { WebWritableStream } from 'htmlparser2';
const WebWritableStream = require('htmlparser2').WebWritableStream;
Introduced in v11.0.0, this enables direct piping from Web Streams API responses.

This quickstart demonstrates the event-driven parsing capabilities of htmlparser2 by creating a `Parser` instance and feeding it HTML content. It logs opening tags, text content, and closing tags, illustrating the callback interface.

import { Parser } from 'htmlparser2'; const htmlContent = "Xyz <script type='text/javascript'>const foo = '<<bar>>';</script><p>Hello, World!</p>"; const parser = new Parser({ onopentag(name, attributes) { console.log(`Opened tag: ${name}`); if (name === "script" && attributes.type === "text/javascript") { console.log("JavaScript block detected!"); } }, ontext(text) { // Note: This can fire at any point within text and you might // have to stitch together multiple pieces if not using a DOM handler. const trimmedText = text.trim(); if (trimmedText.length > 0) { console.log(`--> Text content: '${trimmedText}'`); } }, onclosetag(tagname) { console.log(`Closed tag: ${tagname}`); if (tagname === "script") { console.log("Script block finished."); } }, onerror(error) { console.error("Parsing error:", error); } }); parser.write(htmlContent); parser.end(); // To get a DOM, you'd typically use parseDocument with domhandler: // import { parseDocument } from 'htmlparser2'; // const dom = parseDocument('<div id="root"><span>Hi</span></div>'); // console.log(dom[0].children[0].data); // 'Hi'
Debug
Known issues
breakingAs of v11.0.0, htmlparser2 is an ESM-only module. All CommonJS `require()` statements will fail, and you must migrate to ES Modules `import` syntax.
fix
Update your project to use ES Modules (e.g., `"type": "module"` in `package.json`) and replace all `require('htmlparser2')` with `import { ... } from 'htmlparser2';`.
affects: >=11.0.0
breakingVersion 11.0.0 raises the minimum Node.js version requirement to 20.19.0. Older Node.js environments will not be supported.
fix
Ensure your project's Node.js environment is updated to version 20.19.0 or newer.
affects: >=11.0.0
breakingVersion 12.0.0 aligns HTML parsing with the WHATWG specification, particularly for raw-text and RCDATA tags such as `<iframe>`, `<noembed>`, `<noframes>`, `<plaintext>`, and `<textarea>`. Their content is no longer parsed as HTML, and entities in `<textarea>` are now decoded.
fix
Review existing code that processes content within these tags, as the parsing behavior for their children will have changed. Content previously parsed as HTML will now be treated as raw text.
affects: >=12.0.0
breakingIn v9.0.0, the tokenizer's entity parsing behavior changed to align with the HTML spec, specifically for entities within attributes. This can lead to different attribute values for certain malformed inputs (e.g., `<a href='&amp=boo'>`).
fix
Test parsing of HTML with complex or malformed entities in attributes to ensure the new behavior does not negatively impact your application's logic. Adjust expectations for attribute values as necessary.
affects: >=9.0.0
breakingThe `FeedHandler` class, previously deprecated, has been completely removed in v8.0.0. Code relying on this class will break.
fix
Migrate your feed parsing logic. The documentation or past changelogs for v8.0.0 should provide guidance on how to replace `FeedHandler` functionality, typically by using a generic handler with `parseDocument` and `domutils`.
affects: >=8.0.0
breakingVersion 8.0.0 requires TypeScript >= 4.5. Projects using older TypeScript versions will encounter compilation errors.
fix
Upgrade your project's TypeScript dependency to version 4.5 or newer.
affects: >=8.0.0
gotchahtmlparser2 is optimized for speed and may take shortcuts, meaning it is not strictly HTML spec compliant in all edge cases. For applications requiring strict spec adherence, `parse5` might be a more suitable alternative.
fix
If strict HTML compliance is critical, evaluate if htmlparser2's parsing behavior meets your requirements, especially with highly malformed or unusual HTML inputs. Consider using `parse5` if strictness is paramount.
affects: All versions
Errors
Common errors & fixes
SyntaxError: require is not defined
Attempting to use CommonJS `require()` syntax with htmlparser2 v11.0.0 or later in an ES Modules environment.
fix
Change `const htmlparser2 = require('htmlparser2');` to `import * as htmlparser2 from 'htmlparser2';` or `import { Parser } from 'htmlparser2';`. Ensure your `package.json` has `"type": "module"` if running in Node.js.
TypeError: htmlparser2.FeedHandler is not a constructor
Attempting to instantiate the `FeedHandler` class, which was removed in htmlparser2 v8.0.0.
fix
Refactor your code to no longer use `FeedHandler`. Instead, use the `Parser` class with custom handlers or the `parseDocument` function along with `domutils` and `domhandler` to process feeds.
TS2307: Cannot find module 'htmlparser2' or its corresponding type declarations.
TypeScript compiler cannot locate the module or its types, possibly due to incorrect import paths, missing `@types/htmlparser2` (though it ships types), or an outdated TypeScript version.
fix
Ensure `htmlparser2` is installed. If using an older TypeScript version (<4.5), upgrade it as v8.0.0+ requires TS >= 4.5. Verify your `tsconfig.json` `moduleResolution` is set appropriately for ESM (e.g., `"node16"` or `"bundler"`).
RangeError: Maximum call stack size exceeded
This can occur with extremely large or deeply nested HTML structures due to recursive parsing, especially when building a DOM directly without streaming.
fix
For very large documents, consider using the event-driven `Parser` directly with custom handlers to process chunks incrementally, rather than building a complete DOM tree with `parseDocument`. Increase Node.js stack size (`--stack-size=N`) as a temporary measure if acceptable.
Upgrade
Version history
12.0.0latest on npm
Audit
Dependencies
domhandlerrequiredRequired for building a DOM tree from parsed HTML/XML, commonly used with htmlparser2.
domutilsrequiredProvides utility functions for manipulating the DOM created by domhandler.
domelementtyperequiredDefines the types of DOM elements, used internally by htmlparser2 and domhandler.
entitiesrequiredUsed for decoding and encoding HTML entities, integral to the parsing process.
Agent activity
4 hits · last 30 days
node
4
Resources
htmlparser2 — npm install htmlparser2 · libregistry