WebAssembly 的第一个可流式传输的固定内存 XML、HTML 和 JSX 分析器。
When you absolutely, positively have to have the fastest parser in the room, accept no substitutes.
npm i sax-wasm.SAXParser, load the packaged lib/sax-wasm.wasm, and stream bytes via a reader.Node (ESM):
…Browser:
import { SaxEventType, SAXParser } from 'sax-wasm';
const parser = new SAXParser(SaxEventType.Attribute | SaxEventType.OpenTag);
await parser.prepareWasm(fetch(new URL('sax-wasm/lib/sax-wasm.wasm', import.meta.url)));
const res = await fetch('/document.xml');
for await (const [event, detail] of parser.parse(res.body.getReader())) {
// handle events
}Note: prepareWasm accepts Uint8Array | Response | Promise.
TypeScript note (Node 20+/22): SAXParser.parse expects a ReadableStreamDefaultReader.
Node's Readable.toWeb() often produces a ReadableStream, so the generic type is lost.
You can either type the stream or cast the reader:
// Option A: type the stream
const webStream = Readable.toWeb(createReadStream(xmlUrl)) as ReadableStream;
for await (const [event, detail] of parser.parse(webStream.getReader())) {
// ...
}
// Option B: cast the reader
for await (const [event, detail] of parser.parse(
webStream.getReader() as ReadableStreamDefaultReader
)) {
// ...
}The first streamable, low memory XML, HTML, JSX and Angular Template parser for WebAssembly.
Sax Wasm is a sax style parser for XML, HTML, JSX and Angular Templates written in Rust, compiled for WebAssembly with the sole motivation to bring the fastest possible speeds to XML and JSX parsing for node and the web. Inspired by sax js and rebuilt with Rust for WebAssembly, sax-wasm brings optimizations for speed and support for JSX syntax.
Suitable for LSP implementations, sax-wasm provides line numbers and character positions within the document for elements, attributes and text node which provides the raw building blocks for linting, transpilation and lexing.
The sax-wasm parser provides precise location information for each entity encountered during the parsing process. Here's how you can access and utilize this information:
For each entity, sax-wasm returns a Position object:
line: The line number where the entity begins.character: The column or "character" number where the entity begins.The position data 100% works with xml.substring(start, end) or xml.slice(start, end) and takes into account 2–4 byte graphemes such as emojis, Cyrillic, or UTF‑16 encoded documents.
In addition to line and character positions, sax-wasm now provides byte offset ranges for all entities. This allows for precise byte-level access to the original data:
byteOffsets with:start: The starting byte position in the original dataend: The ending byte position in the original dataThis is particularly useful for:
The parser distinguishes between different attribute syntax types (see AttributeType in src/js/saxWasm.ts):
disabled)prop={expression})attr=value)attr='value')attr="value")This information is available in the type field of each attribute and can be used for syntax highlighting, linting, or format‑specific processing.
When parsing , you might receive output like this:
Preview:
{
"openStart": { "line": 0, "character": 0 },
"openEnd": { "line": 0, "character": 19 },
"closeStart":{ "line": 0, "character": 33 },
"closeEnd": { "line": 0, "character": 39 },
"name": "div",
"attributes": [ { "name": { "value": "class" }, "value": { "value": "myDiv" } } ],
"textNodes": [ { "value": "This is my div" } ],
"selfClosing": false
}Full details:
Show full example
…Benchmarks last updated: 2026-02-12. Reproduce locally with:
npm install
npm run build:wasm
npm run benchmarkThe benchmark script (src/js/__test__/benchmark.mjs) streams the bundled src/js/__test__/xml.xml (≈3 MB) from memory to minimize disk variance and reports the mean over 10 runs.
Values below are the mean of 10 benchmark batches (100 internal runs per parser).
Run recorded on macOS Apple Silicon (arm64).
| Parser with Advanced Features | time/ms (lower is better) | JS | Runs in browser |
|---|---|---|---|
| sax-wasm | 6.80 | ☑ | ☑ |
| saxes | 11.00 | ☑ | ☑ |
| ltx(using Saxes as the parser) | 11.56 | ☑ | ☑ |
| sax-js | 26.99 | ☑ | ☑* |
| node-xml | 31.73 | ☑ | ☐ |
| node-expat | 41.51 | ☑ | ☐ |
| *built for node but should run in the browser |
Install once, then jump back to Quickstart for minimal usage:
npm i sax-wasmSupports Node (>=18.20.5) with both ESM and CJS entry points and modern browsers.
…CommonJS:
…NOTE This uses WebAssembly.instantiateStreaming under the hood to load the wasm.
…Tag, Attribute, ProcInst and Text objects received from the parsing operation have a 'lifetime' that is limited to the eventHandler() or the function loop body for the *parse() generator. Data sent across the FFI (Foreign Function Interface) boundary is read directly from WASM memory which is partly why sax-wasm is so fast. This comes with the tradeoff that this memory is temporary because it is overwritten on the next write operation. If you need to persist the event data for long term use, call toJSON() on each object as needed. This comes at a slight performance cost and should not be necessary for the vast majority of use cases.
| Feature / Behavior | sax-wasm stance |
|---|---|
| Maintenance | Actively maintained |
| Encoding | UTF‑8/UTF‑16; 1–4 byte graphemes preserved even across chunk boundaries |
| JSX | Supported (including fragments) |
| Angular templates | Supported (e.g., bindings, structural directives, event handlers) |
| HTML | Supported (non-quirks mode) |
| Validation | Non-validating; emits what it sees—apply your own rules for strict mode |
| Namespaces | Reported in attributes; no dedicated namespace events |
| Streaming input | Requires streaming UTF‑8 bytes (Uint8Array) |
| Inter-element whitespace | Not emitted; infer via positions or enable Text and filter |
| Byte offsets | Provided for all entities for direct byte slicing |
| Attribute types | Reported (no‑value, JSX, unquoted, single, double quoted) |
Streaming is supported with sax-wasm by writing utf-8 code points (Uint8Array) to the parser instance. Writes can occur safely
anywhere except within the eventHandler function or within the eventTrap (when extending SAXParser class).
Doing so anyway risks overwriting memory still in play.
Events are subscribed to using a bitmask composed from flags representing the event type. For example, passing in the following bitmask to the parser instructs it to emit events for Text, OpenTag and Attribute:
import { SaxEventType } from 'sax-wasm';
parser.events = SaxEventType.Text | SaxEventType.OpenTag | SaxEventType.Attribute;Complete list of event/argument pairs:
| Event | Mask | Argument passed to handler |
|---|---|---|
| SaxEventType.Text | 0b1 | text: Text |
| SaxEventType.ProcessingInstruction | 0b10 | procInst: ProcInst |
| SaxEventType.Declaration | 0b100 | declaration: Text |
| SaxEventType.Doctype | 0b1000 | doctype: Text |
| SaxEventType.Comment | 0b10000 | comment: Text |
| SaxEventType.OpenTagStart | 0b100000 | tag: Tag |
| SaxEventType.Attribute | 0b1000000 | attribute: Attribute |
| SaxEventType.OpenTag | 0b10000000 | tag: Tag |
| SaxEventType.CloseTag | 0b100000000 | tag: Tag |
| SaxEventType.Cdata | 0b1000000000 | text: Text |
Note: In prose you may see “CDATA”, but the enum value is spelled Cdata.
Whitespace-only text nodes between elements are intentionally not emitted to keep streaming performance high. If you need to account for inter-element whitespace, compare the line/character positions of consecutive tags to infer gaps.
| Concern | Do this | Why it helps |
|---|---|---|
| Input format | Stream Uint8Array bytes directly (avoid loading XML as string and re-encoding) |
Skips JS-side encoding overhead; parser often finishes as the download ends |
| Events requested | Keep the events bitmask minimal |
Less JS work per callback, fewer conversions |
| Property access | Read only what you need; avoid bulk JSON.stringify() |
First access performs the costly decode; later reads are cac |
暂无开放 Issues,或尚未同步最近议题。