Getting Started
Installation and first steps with WebKLV
Getting Started
Installation
npm install webklv
# or
pnpm add webklv
# or
yarn add webklvBasic Parsing
Raw KLV Buffer
Parse a raw buffer using KLVParser for the lowest-level access:
import { KLVParser } from "webklv";
const buffer = new Uint8Array([0x02, 0x08, 0x00, 0x04, 0x60, 0x50, 0x58, 0x4e, 0x01, 0x80]);
const parser = new KLVParser(buffer, { keyLength: 1 });
for (const { key, value } of parser) {
console.log("Key:", key); // Uint8Array [2]
console.log("Value:", value); // Uint8Array [0, 4, 96, 80, ...]
}MISB ST 0601 Stream
For MISB packets, use StreamParser which dispatches 16-byte Universal Labels:
import { StreamParser, UASLocalMetadataSet, PrecisionTimeStamp } from "webklv";
for (const packet of new StreamParser(buffer)) {
if (packet instanceof UASLocalMetadataSet) {
// Access child elements
for (const [keyHex, element] of packet.items) {
console.log(element.toString());
}
}
}Encoding Values
Every element can be re-encoded to its wire format:
import { PlatformHeadingAngle, SensorLatitude } from "webklv";
// Encode from a number
const heading = new PlatformHeadingAngle(159.974);
console.log(heading.toBytes()); // Uint8Array [0x05, 0x02, 0x71, 0xC2]
// Decode from bytes, then re-encode
const bytes = new Uint8Array([0x71, 0xC2]);
const decoded = new PlatformHeadingAngle(bytes);
console.log(decoded.value.toString()); // "159.97436484321355"
console.log(decoded.toBytes()); // Uint8Array [0x05, 0x02, 0x71, 0xC2]Working with Timestamps
Precision timestamps use microsecond precision via BigInt internally:
import { PrecisionTimeStamp } from "webklv";
const bytes = new Uint8Array([0x00, 0x04, 0x60, 0x50, 0x58, 0x4E, 0x01, 0x80]);
const ts = new PrecisionTimeStamp(bytes);
console.log(ts.value.toString()); // "2009-01-12 22:08:22+00:00"
console.log(ts.value.value); // Date objectError Handling
import { KLVParser, TruncatedDataError, BERDecodeError } from "webklv";
try {
const parser = new KLVParser(truncatedBuffer, { keyLength: 16 });
for (const item of parser) { ... }
} catch (err) {
if (err instanceof TruncatedDataError) {
console.error("Buffer ended unexpectedly:", err.message);
}
}