Registry / serialization / sax-ts

sax-ts

JSON →
library1.2jsnpmunverified

sax-ts is an event-driven SAX-style parser for XML and HTML, fully implemented in TypeScript. It is designed with Deno in mind, ensuring browser compatibility, and is also available for Node.js via npm and JSR. The current stable version is 1.2.13, with a release cadence that includes recent point releases for fixes and platform support. Key differentiators include its TypeScript-first approach, memory efficiency for handling large XML documents (e.g., '80 GB' parsing without burning a laptop), and its ability to robustly parse both well-formed and 'mostly-ok-but-kinda-broken' XML documents often found in feeds like RSS. Forked from `sax-js` at version 1.2.9, it aims to provide a modern, type-safe alternative across multiple JavaScript runtimes, supporting strict XML parsing and more forgiving HTML parsing.

npm install sax-ts
INSTALL
IMPORT
SIG · SAX-TS
S
sax-ts
serializationjavascriptv1.2
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.

SAXParser
import { SAXParser } from 'sax-ts';
const { SAXParser } = require('sax-ts');
For Node.js projects, use ESM imports. While the package might offer dual CommonJS exports, ESM is the recommended and type-safe approach for modern Node.js and TypeScript.
SAXParser (Deno)
import { SAXParser } from 'https://deno.land/x/sax_ts@1.2.13/mod.ts';
import { SAXParser } from 'https://deno.land/x/sax_ts/src/sax.ts';
For Deno, import directly from `deno.land/x`. Use the `mod.ts` entry point which is standard for Deno third-party modules, and pin the exact version for stable, immutable imports.
SAXParser (JSR)
import { SAXParser } from '@maxim-mazurok/sax_ts';
import { SAXParser } from 'sax-ts';
When using JSR (for Deno, Node.js, Bun), import using the scoped package name as published to JSR. JSR packages are distinct from npm packages.
EVENTS
import { EVENTS } from 'sax-ts';
The `EVENTS` array lists all supported event names as strings, useful for programmatic event registration.

This quickstart demonstrates how to instantiate `SAXParser`, configure its strictness and options, register event handlers for common XML elements (tags, text, errors), and parse a multi-line XML string to extract structured data. It highlights the event-driven nature of the parser and proper error handling.

import { SAXParser, EVENTS } from 'sax-ts'; // Example XML string to parse const xmlString = ` <bookstore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2205</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> `; const strict: boolean = false; // Set to true for strict XML parsing; false for more permissive (HTML-like) parsing const options = { trim: true, // Trim text and comment nodes normalize: true, // Turn any whitespace into a single space lowercase: true, // Lowercase tag and attribute names in loose mode xmlns: true, // Support namespaces position: true, // Track line/col/position strictEntities: true // Only parse predefined XML entities: &amp; &apos; &gt; &lt; &quot; }; const parser = new SAXParser(strict, options); let currentTag: string | null = null; let currentText: string = ''; const parsedBooks: any[] = []; let currentBook: any = {}; parser.onerror = function (e: Error) { console.error(`Parser error: ${e.message}`); // Crucially, you must clear the error and resume to continue parsing. (this as SAXParser).error = null; (this as SAXParser).resume(); }; parser.onopentag = function (node) { currentTag = node.name; if (node.name === 'book') { currentBook = { attributes: node.attributes, content: {} }; } }; parser.onclosetag = function (tagName) { if (currentTag && currentText.trim()) { if (currentBook.content) { currentBook.content[currentTag] = currentText.trim(); } } currentText = ''; currentTag = null; if (tagName === 'book') { parsedBooks.push(currentBook); currentBook = {}; } }; parser.ontext = function (t) { if (currentTag) { currentText += t; } }; parser.onend = function () { console.log('XML parsing completed.'); console.log('Parsed Books:', JSON.stringify(parsedBooks, null, 2)); }; console.log(`Starting XML parsing. Supported events: ${EVENTS.join(', ')}`); parser.write(xmlString).close();
Debug
Known issues
breakingThis package is a fork of `sax-js`. While API-compatible, there might be subtle behavioral differences or changes in how specific edge cases are handled since its fork at v1.2.9. Users migrating from `sax-js` should verify functionality.
fix
Thoroughly test existing XML parsing logic after upgrading or migrating from `sax-js`. Review changelogs for any specific deviations if issues arise.
affects: >=1.2.9
gotchaAfter an `error` event, the parser enters an error state and will not continue parsing until the `parser.error` property is explicitly cleared (set to `null`) and `parser.resume()` is called. Failure to do so will halt parsing indefinitely.
fix
Implement an `onerror` handler that clears `(this as SAXParser).error = null;` and calls `(this as SAXParser).resume();` to recover from errors and continue parsing.
affects: >=1.0.0
gotchaThe `strict` option significantly changes parsing behavior. When `true`, it enforces strict XML well-formedness. When `false` (default), it's more forgiving, suitable for HTML or malformed XML, but may produce unexpected results for strictly conforming XML documents.
fix
Carefully choose the `strict` option based on the input document type (XML vs. HTML) and desired parsing robustness. Defaulting to `false` is often appropriate for varied web content, while `true` is for precise XML validation.
affects: >=1.0.0
gotchaWhen importing `sax-ts` in Deno, it's crucial to pin to a specific version in the URL (e.g., `@1.2.13`) to ensure immutability and prevent unexpected breaking changes from newer versions.
fix
Always include the exact version in Deno import URLs, e.g., `https://deno.land/x/sax_ts@1.2.13/mod.ts`. Utilize Deno's `deno.lock` for integrity checking.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: SAXParser is not a constructor
Attempting to use `require()` for an ESM-first or ESM-only package in a CommonJS context, or incorrect named import syntax.
fix
Ensure your Node.js project uses ESM imports: `import { SAXParser } from 'sax-ts';`. If you must use CommonJS, ensure your environment and package configuration correctly support dual ESM/CJS or try dynamic import: `import('sax-ts').then(({ SAXParser }) => { /* ... */ });`.
Parser error: Invalid character in tag name
The input XML/HTML contains characters in tag names that are not allowed by the XML specification, and the parser is running in `strict` mode.
fix
Either correct the malformed XML input, or initialize `SAXParser` with `strict: false` to enable a more forgiving parsing mode for HTML or less strict XML documents.
Parsing suspended: error occurred
An error was encountered during parsing (e.g., malformed XML in strict mode), and the `onerror` handler did not clear the internal error state or call `resume()`.
fix
In your `onerror` handler, set `(this as SAXParser).error = null;` to clear the error, and then call `(this as SAXParser).resume();` to allow the parser to continue processing the stream.
Upgrade
Version history
1.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
14 hits · last 30 days
node
12
OpenAI (training)
1
Resources