{"name":"htmlparser2","version":"12.0.0","keywords":["html","parser","streams","xml","dom","rss","feed","atom"],"author":{"name":"Felix Boehm","email":"me@feedic.com"},"license":"MIT","_id":"htmlparser2@12.0.0","maintainers":[{"name":"fb55","email":"me@feedic.com"}],"homepage":"https://github.com/fb55/htmlparser2#readme","bugs":{"url":"https://github.com/fb55/htmlparser2/issues"},"dist":{"shasum":"6a679d0f57c525990f9cbad8a585b320ecc6d198","tarball":"http://registry-npm.ywwl.com/htmlparser2/download/htmlparser2-12.0.0.tgz","fileCount":28,"integrity":"sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw==","signatures":[{"sig":"MEUCIEM+OojklJ4lCVOSwzGute0EEevjGImq5dOmwZMIfRMcAiEAnJyRv/aLJAouvHQdRuAQrfmp8Zgp9RZOEnuISl5dKG0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/htmlparser2@12.0.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":235104,"size":44710,"noattachment":false,"key":"/htmlparser2/-/htmlparser2-12.0.0.tgz"},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","engines":{"node":">=20.19.0"},"exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./WritableStream":{"types":"./dist/WritableStream.d.ts","default":"./dist/WritableStream.js"},"./WebWritableStream":{"types":"./dist/WebWritableStream.d.ts","default":"./dist/WebWritableStream.js"}},"funding":["https://github.com/fb55/htmlparser2?sponsor=1",{"url":"https://github.com/sponsors/fb55","type":"github"}],"gitHead":"c73fec0c0586647cd1269d2598e2ba4203d0207f","scripts":{"lint":"npm run lint:es && npm run lint:ts && npm run lint:biome","test":"npm run test:vi && npm run lint","build":"tsc","format":"npm run format:es && npm run format:biome","lint:es":"eslint .","lint:ts":"tsc --noEmit","test:vi":"vitest run","format:es":"npm run lint:es -- --fix","lint:biome":"biome check .","format:biome":"biome check --write .","prepublishOnly":"npm run build"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:b7d19ccf-db7c-4a59-8d26-d2b0d7f977ce"}},"repository":{"url":"git://github.com/fb55/htmlparser2.git","type":"git"},"_npmVersion":"11.9.0","description":"Fast & forgiving HTML/XML parser","directories":{},"sideEffects":false,"_nodeVersion":"24.14.0","dependencies":{"domutils":"^4.0.2","entities":"^8.0.0","domhandler":"^6.0.0","domelementtype":"^3.0.0"},"_hasShrinkwrap":false,"devDependencies":{"eslint":"^10.0.3","vitest":"^4.1.0","typescript":"^5.9.3","@types/node":"^25.5.0","@biomejs/biome":"^2.4.8","typescript-eslint":"^8.57.1","eslint-config-biome":"^2.1.3","@feedic/eslint-config":"^0.3.1"},"_npmOperationalInternal":{"tmp":"tmp/htmlparser2_12.0.0_1774048119840_0.268223020778972","host":"s3://npm-registry-packages-npm-production"},"readme":"# htmlparser2\n\n[![NPM version](https://img.shields.io/npm/v/htmlparser2.svg)](https://npmjs.org/package/htmlparser2)\n[![Downloads](https://img.shields.io/npm/dm/htmlparser2.svg)](https://npmjs.org/package/htmlparser2)\n[![Node.js CI](https://github.com/fb55/htmlparser2/actions/workflows/nodejs-test.yml/badge.svg)](https://github.com/fb55/htmlparser2/actions/workflows/nodejs-test.yml)\n[![Coverage](https://img.shields.io/coveralls/fb55/htmlparser2.svg)](https://coveralls.io/r/fb55/htmlparser2)\n\nThe fast & forgiving HTML/XML parser.\n\n_htmlparser2 is [the fastest HTML parser](#performance), and takes some shortcuts to get there. If you need strict HTML spec compliance, have a look at [parse5](https://github.com/inikulin/parse5)._\n\n## Installation\n\n    npm install htmlparser2\n\nA live demo of `htmlparser2` is available [on AST Explorer](https://astexplorer.net/#/2AmVrGuGVJ).\n\n## Ecosystem\n\n| Name                                                          | Description                                             |\n| ------------------------------------------------------------- | ------------------------------------------------------- |\n| [htmlparser2](https://github.com/fb55/htmlparser2)            | Fast & forgiving HTML/XML parser                        |\n| [domhandler](https://github.com/fb55/domhandler)              | Handler for htmlparser2 that turns documents into a DOM |\n| [domutils](https://github.com/fb55/domutils)                  | Utilities for working with domhandler's DOM             |\n| [css-select](https://github.com/fb55/css-select)              | CSS selector engine, compatible with domhandler's DOM   |\n| [cheerio](https://github.com/cheeriojs/cheerio)               | The jQuery API for domhandler's DOM                     |\n| [dom-serializer](https://github.com/cheeriojs/dom-serializer) | Serializer for domhandler's DOM                         |\n\n## Usage\n\n`htmlparser2` itself provides a callback interface that allows consumption of documents with minimal allocations.\nFor a more ergonomic experience, read [Getting a DOM](#getting-a-dom) below.\n\n```js\nimport * as htmlparser2 from \"htmlparser2\";\n\nconst parser = new htmlparser2.Parser({\n    onopentag(name, attributes) {\n        /*\n         * This fires when a new tag is opened.\n         *\n         * If you don't need an aggregated `attributes` object,\n         * have a look at the `onopentagname` and `onattribute` events.\n         */\n        if (name === \"script\" && attributes.type === \"text/javascript\") {\n            console.log(\"JS! Hooray!\");\n        }\n    },\n    ontext(text) {\n        /*\n         * Fires whenever a section of text was processed.\n         *\n         * Note that this can fire at any point within text and you might\n         * have to stitch together multiple pieces.\n         */\n        console.log(\"-->\", text);\n    },\n    onclosetag(tagname) {\n        /*\n         * Fires when a tag is closed.\n         *\n         * You can rely on this event only firing when you have received an\n         * equivalent opening tag before. Closing tags without corresponding\n         * opening tags will be ignored.\n         */\n        if (tagname === \"script\") {\n            console.log(\"That's it?!\");\n        }\n    },\n});\nparser.write(\n    \"Xyz <script type='text/javascript'>const foo = '<<bar>>';</script>\",\n);\nparser.end();\n```\n\nOutput (with multiple text events combined):\n\n```\n--> Xyz\nJS! Hooray!\n--> const foo = '<<bar>>';\nThat's it?!\n```\n\n### Parser events\n\nAll callbacks are optional. The handler object you pass to `Parser` may implement any subset of these:\n\n| Event                                        | Description                                                                                                                                      |\n| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `onopentag(name, attribs, isImplied)`        | Opening tag. `attribs` is an object mapping attribute names to values. `isImplied` is `true` when the tag was opened implicitly (HTML mode only). |\n| `onopentagname(name)`                        | Emitted for the tag name as soon as it is available (before attributes are parsed).                                                              |\n| `onattribute(name, value, quote)`            | Attribute. `quote` is `\"` / `'` / `null` (unquoted) / `undefined` (no value, e.g. `disabled`).                                                  |\n| `onclosetag(name, isImplied)`                | Closing tag. `isImplied` is `true` when the tag was closed implicitly (HTML mode only).                                                          |\n| `ontext(data)`                               | Text content. May fire multiple times for a single text node.                                                                                    |\n| `oncomment(data)`                            | Comment (content between `<!--` and `-->`).                                                                                                      |\n| `oncdatastart()`                             | Opening of a CDATA section (`<![CDATA[`).                                                                                                        |\n| `oncdataend()`                               | End of a CDATA section (`]]>`).                                                                                                                  |\n| `onprocessinginstruction(name, data)`        | Processing instruction (e.g. `<?xml ...?>`).                                                                                                     |\n| `oncommentend()`                             | Fires after a comment has ended.                                                                                                                 |\n| `onparserinit(parser)`                       | Fires when the parser is initialized or reset.                                                                                                   |\n| `onreset()`                                  | Fires when `parser.reset()` is called.                                                                                                           |\n| `onend()`                                    | Fires when parsing is complete.                                                                                                                  |\n| `onerror(error)`                             | Fires on error.                                                                                                                                  |\n\n### Parser options\n\n| Option                   | Type      | Default    | Description                                                                                                                                              |\n| ------------------------ | --------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `xmlMode`                | `boolean` | `false`    | Treat the document as XML. This affects entity decoding, self-closing tags, CDATA handling, and more. Set this to `true` for XML, RSS, Atom and RDF feeds. |\n| `decodeEntities`         | `boolean` | `true`     | Decode HTML entities (e.g. `&amp;` -> `&`).                                                                                                              |\n| `lowerCaseTags`          | `boolean` | `!xmlMode` | Lowercase tag names.                                                                                                                                     |\n| `lowerCaseAttributeNames`| `boolean` | `!xmlMode` | Lowercase attribute names.                                                                                                                               |\n| `recognizeSelfClosing`   | `boolean` | `xmlMode`  | Recognize self-closing tags (e.g. `<br/>`). Always enabled in `xmlMode`.                                                                                 |\n| `recognizeCDATA`         | `boolean` | `xmlMode`  | Recognize CDATA sections as text. Always enabled in `xmlMode`.                                                                                           |\n\n### Usage with streams\n\nWhile the `Parser` interface closely resembles Node.js streams, it's not a 100% match.\nUse the `WritableStream` interface to process a streaming input:\n\n```js\nimport { WritableStream } from \"htmlparser2/WritableStream\";\n\nconst parserStream = new WritableStream({\n    ontext(text) {\n        console.log(\"Streaming:\", text);\n    },\n});\n\nconst htmlStream = fs.createReadStream(\"./my-file.html\");\nhtmlStream.pipe(parserStream).on(\"finish\", () => console.log(\"done\"));\n```\n\n## Getting a DOM\n\nThe `parseDocument` helper parses a string and returns a DOM tree (a [`Document`](https://github.com/fb55/domhandler) node).\n\n```js\nimport * as htmlparser2 from \"htmlparser2\";\n\nconst dom = htmlparser2.parseDocument(\n    `<ul id=\"fruits\">\n        <li class=\"apple\">Apple</li>\n        <li class=\"orange\">Orange</li>\n    </ul>`,\n);\n```\n\n`parseDocument` accepts an optional second argument with both parser and [DOM handler options](https://github.com/fb55/domhandler):\n\n```js\nconst dom = htmlparser2.parseDocument(data, {\n    // Parser options\n    xmlMode: true,\n\n    // domhandler options\n    withStartIndices: true, // Add `startIndex` to each node\n    withEndIndices: true,   // Add `endIndex` to each node\n});\n```\n\n### Searching the DOM\n\nThe [`DomUtils`](https://github.com/fb55/domutils) module (re-exported on the main `htmlparser2` export) provides helpers for finding nodes:\n\n```js\nimport * as htmlparser2 from \"htmlparser2\";\n\nconst dom = htmlparser2.parseDocument(`<div><p id=\"greeting\">Hello</p></div>`);\n\n// Find elements by ID, tag name, or class\nconst greeting = htmlparser2.DomUtils.getElementById(\"greeting\", dom);\nconst paragraphs = htmlparser2.DomUtils.getElementsByTagName(\"p\", dom);\n\n// Find elements with custom test functions\nconst all = htmlparser2.DomUtils.findAll(\n    (el) => el.attribs?.class === \"active\",\n    dom,\n);\n\n// Get text content\nhtmlparser2.DomUtils.textContent(greeting); // \"Hello\"\n```\n\nFor CSS selector queries, use [`css-select`](https://github.com/fb55/css-select):\n\n```js\nimport { selectAll, selectOne } from \"css-select\";\n\nconst results = selectAll(\"ul#fruits > li\", dom);\nconst first = selectOne(\"li.apple\", dom);\n```\n\nOr, if you'd prefer a jQuery-like API, use [`cheerio`](https://github.com/cheeriojs/cheerio).\n\n### Modifying and serializing the DOM\n\nUse `DomUtils` to modify the tree, and [`dom-serializer`](https://github.com/cheeriojs/dom-serializer) (also available as `DomUtils.getOuterHTML`) to serialize it back to HTML:\n\n```js\nimport * as htmlparser2 from \"htmlparser2\";\n\nconst dom = htmlparser2.parseDocument(\n    `<ul><li>Apple</li><li>Orange</li></ul>`,\n);\n\n// Remove the first <li>\nconst items = htmlparser2.DomUtils.getElementsByTagName(\"li\", dom);\nhtmlparser2.DomUtils.removeElement(items[0]);\n\n// Serialize back to HTML\nconst html = htmlparser2.DomUtils.getOuterHTML(dom);\n// \"<ul><li>Orange</li></ul>\"\n```\n\nOther manipulation helpers include `appendChild`, `prependChild`, `append`, `prepend`, and `replaceElement` -- see the [`domutils` docs](https://github.com/fb55/domutils) for the full API.\n\n## Parsing feeds\n\n`htmlparser2` makes it easy to parse RSS, RDF and Atom feeds, by providing a `parseFeed` method:\n\n```javascript\nconst feed = htmlparser2.parseFeed(content);\n```\n\nThis returns an object with `type`, `title`, `link`, `description`, `updated`, `author`, and `items` (an array of feed entries), or `null` if the document isn't a recognized feed format.\n\nThe `xmlMode` option is enabled by default for `parseFeed`. If you pass custom options, make sure to include `xmlMode: true`.\n\n## Performance\n\nAfter having some artificial benchmarks for some time, **@AndreasMadsen** published his [`htmlparser-benchmark`](https://github.com/AndreasMadsen/htmlparser-benchmark), which benchmarks HTML parses based on real-world websites.\n\nAt the time of writing, the latest versions of all supported parsers show the following performance characteristics on GitHub Actions (sourced from [here](https://github.com/AndreasMadsen/htmlparser-benchmark/blob/e78cd8fc6c2adac08deedd4f274c33537451186b/stats.txt)):\n\n```\nhtmlparser2        : 2.17215 ms/file ± 3.81587\nnode-html-parser   : 2.35983 ms/file ± 1.54487\nhtml5parser        : 2.43468 ms/file ± 2.81501\nneutron-html5parser: 2.61356 ms/file ± 1.70324\nhtmlparser2-dom    : 3.09034 ms/file ± 4.77033\nhtml-dom-parser    : 3.56804 ms/file ± 5.15621\nlibxmljs           : 4.07490 ms/file ± 2.99869\nhtmljs-parser      : 6.15812 ms/file ± 7.52497\nparse5             : 9.70406 ms/file ± 6.74872\nhtmlparser         : 15.0596 ms/file ± 89.0826\nhtml-parser        : 28.6282 ms/file ± 22.6652\nsaxes              : 45.7921 ms/file ± 128.691\nhtml5              : 120.844 ms/file ± 153.944\n```\n\n## Security contact information\n\nTo report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security).\nTidelift will coordinate the fix and disclosure.\n","publish_time":1774048119985,"_cnpm_publish_time":1774048119985,"dist-tags":{"latest":"12.0.0"}}