Binpat simplifies parsing binary data in JavaScript by allowing you to define the data structure using declarative patterns.
- Declarative: Define what your data looks like, no more manual
DataView
operations and offsets. - Readable: Patterns often closely resemble the desired output object structure.
- Almost Type Safe: Built with TypeScript, providing inferred return types based on your patterns.
- However for
omit()
andspread()
, I'm failed to pass the type gymnastics, help is welcomed.
- However for
- Common types:
u8
...u64
,i8
...i64
,f16
...f64
,bool
,string
,bitfield
andarray(pattern, size)
. - Conditional parsing with
ternary(condition, truthy, falsy)
. - Transform parsed values using
convert(pattern, fn)
. - Control parsing offset with
skip(offset)
,seek(offset)
andpeek(offset, pattern)
. - Modify output structure with
omit()
(exclude fields) andspread()
(flatten fields).
npm i binpat
deno add jsr:@aho/binpat
import Binpat from 'https://cdn.jsdelivr.net/npm/binpat/dist/binpat.js';
import Binpat from 'https://unpkg.com/binpat/dist/binpat.js';
import Binpat, { u8, u16, string, array } from 'binpat';
const filePattern = {
fileType: string(4), // e.g., 'DATA'
version: u8(), // e.g., 1
numRecords: u16(), // e.g., 2 records
// Read 'numRecords' count of { id: u8, value: u8 }
records: array({ id: u8(), value: u8() }, (ctx) => ctx.data.numRecords)
};
const binpat = new Binpat(filePattern, { endian: 'big' });
const sampleData = new Uint8Array([
0x44, 0x41, 0x54, 0x41, // 'DATA'
0x01, // version 1
0x00, 0x02, // numRecords 2 (Big Endian)
0x01, 0x64, // Record 1: id=1, value=100
0x02, 0xC8 // Record 2: id=2, value=200
]);
const result = binpat.exec(sampleData.buffer);
console.log(result);
/*
{
fileType: 'DATA',
version: 1,
numRecords: 2,
records: [
{ id: 1, value: 100 },
{ id: 2, value: 200 },
],
}
*/
Find the full API details in the docs and more complex examples in the examples directory.