js-struct
Simplified access to complex byte structures in JavaScript.
js-struct makes it easy to access data in binary buffers. Multi-byte fields, byte arrays, and C-style structs can all be extracted from typed arrays.
const Inode = ;
Installing
npm install js-struct
Getting started
js-struct provides tools to pull usable JS primitives, arrays, and objects out of raw bytes. All data is designed to be fetched from Uint8Arrays
, which can wrap ECMAScript ArrayBuffers
or Node.js Buffers
.
The library contains three ways to structure the data: pre-defined Types, Arrays, and custom Structs. These can be composed in various ways to describe the layout of byte data.
// Read the unsigned 16-bit number at index 10 of `arr`let num = Typeuint16; // Fetch an array of 4 bytes, starting at index 0let bytes = Type; // Retrieve an array of 10 Pointsconst Point = ;let points = Type;
Supported types
The following types are available as properties on require('js-struct').Types
uint8
, unsigned 8-bit integerbyte
, alias foruint8
int8
, signed 8-bit integeruint16
, unsigned 16-bit integerushort
, alias foruint16
int16
, signed 16-bit integershort
, alias foruint16
uint32
, unsigned 32-bit integerulong
, alias foruint32
int32
, signed 32-bit integerlong
, alias forint32
char
, similar tobyte
, but renders as a String
Any of these types can be read directly from an Uint8Array
, with the .read(source, index)
method. As parameters, it takes the typed array, and a byte-aligned index to begin reading from.
An array of any type can be constructed as well, with Type.array()
. It is a method that takes a type, and a numeric size. Arrays share the same .read()
method as the standard types.
Finally, it is possible to construct more complex objects with require('js-struct').Struct
. Struct
is a method that takes an array of fields.
To allow naming of fields on a Struct, all Types, Arrays, and Structs themselves are also functions that take a field name.
let s = ; // Calling s.read() will return an object with two fields console;// {// fieldA: ...,// fieldB: ...,// }