Skip to main content
The @zon-lib/zon package brings Rust-level performance to Node.js environments.

Installation

npm install @zon-lib/zon

Serialization

serialize(data: Object) -> Uint8Array
fn
Converts a JavaScript object directly into a ZON binary buffer.Supported Types:
  • Strings
  • Numbers (Integer)
  • Nested Objects (Coming Soon)
const { serialize } = require('@zon-lib/zon');

const buffer = serialize({ name: "Alice", score: 100 });

Deserialization (Reader)

The ZonReader class wraps the binary buffer.

Constructor

new ZonReader(buffer: Uint8Array)
constructor
Initializes the reader. Throws if the magic header is invalid.
const reader = new ZonReader(buffer);

Methods

rootOffset
getter property
Returns the offset to the root data item defined in the file header.
const root = reader.rootOffset;
readString(offset: number) -> string
method
Reads a UTF-8 string from the given offset.
const name = reader.readString(offset);
readU32(offset: number) -> number
method
Reads an unsigned 32-bit integer from the given offset.
const age = reader.readU32(offset);
len() -> number
method
Returns the total length of the buffer.

Writing Data (Writer)

For advanced usage, use ZonWriter to build a buffer manually.

Constructor

new ZonWriter()
constructor
Initializes a new empty writer.

Methods

writeString(val: string) -> number
method
Writes a string and returns its offset.
writeU32(val: number) -> number
method
Writes a 32-bit integer and returns its offset.
setRoot(offset: number)
method
Sets the root offset for the file.
toBytes() -> Uint8Array
method
Returns the final binary buffer.

Memory Management

Zero-Copy in JS?

When you pass a Buffer or Uint8Array to ZonReader, the WASM memory view is created over that buffer. Warning: If you modify the underlying buffer while the reader is active, you may read corrupt data.

Error Handling

The reader methods throws standard JavaScript Error objects if the access is invalid. You should wrap read operations in try/catch blocks if dealing with untrusted input.
try {
  const val = reader.readU32(999999); // Out of bounds
} catch (e) {
  console.error(e.message); 
  // Output: "Read out of bounds" or "Invalid UTF-8"
}
Common Errors:
  • Buffer too small for ZonHeader: The provided buffer is < 50 bytes.
  • Invalid Magic Number: The file does not start with ZON1.
  • Read out of bounds: Attempted to read past the end of the buffer.