Node HTML Better Parser is a high-performance HTML parser for Node.js and TypeScript, currently at version 1.5.8 and last published 6 months ago. It serves as a fork of `fast-html-parser`, prioritizing speed to process large HTML files efficiently. It generates a simplified Document Object Model (DOM) and includes basic element query support. A key differentiator of this fork is its focus on providing a simpler API for editing HTML and its attributes, which was a primary motivation for its creation. While highly optimized for performance, it may not correctly parse all malformed HTML, though it handles common errors like missing closing tags for `<li>` or `<td>`. The library offers configurable options to retrieve content from `<script>`, `<style>`, `<pre>`, and comments, but users should note these options can slightly impact parsing performance.
npm install node-html-better-parserVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates parsing an HTML string, querying elements by ID and class, accessing their properties, retrieving script and style content using options, and modifying an element's content, then printing the resulting HTML.
Ensure input HTML is as well-formed as possible. For highly unpredictable or malicious HTML, consider pre-processing or using a more robust, but potentially slower, parser that aims for W3C compliance like `parse5`.
Only enable parsing options (e.g., `script: true`, `style: true`) if you explicitly need to retrieve their content. Avoid `lowerCaseTagName` unless strictly necessary for your application's logic.
If frequently accessing `text`, be aware of the initial performance cost. For operations requiring the raw, unescaped text content, use `text`. If performance is paramount and escaped text is acceptable, `rawText` might be more suitable or pre-calculate `text` once if needed repeatedly.
For ESM, use `import { parse } from 'node-html-better-parser';`. For CommonJS, use `const HTMLParser = require('node-html-better-parser');` and then `HTMLParser.parse(html)`. Do not use `const { parse } = require('node-html-better-parser');` directly if the module's main export is not a direct object with a `parse` property when using CommonJS (though for this library, it usually works).Always check the return value of `parse` and `querySelector` calls. The `parse` function returns a fictive root node. Access its children via `root.childNodes` or `root.firstChild` to ensure you're querying actual HTML elements. For example, `const root = parse(html); if (root && root.querySelector) { /* ... */ }`.No dependency data recorded yet.