Binary Parser and Encoder

1.5.3 · active · verified Tue Apr 21

binary-parser-encoder is a JavaScript/TypeScript library designed for declaratively building binary data parsers and encoders. It stands as a feature-rich fork of the popular `binary-parser` project, notably extending its capabilities by adding an `encode` method to convert JavaScript objects back into binary buffers—a key differentiator absent in the original library. The current stable version, 1.5.3, has recently incorporated updates from the upstream `binary-parser` v1.7.0, ensuring continued compatibility while expanding functionality. The library dynamically generates and compiles parser/encoder code on-the-fly, achieving performance comparable to hand-written implementations. It supports a comprehensive set of data types including 8-bit to 64-bit integers, floating-point numbers, bit fields, strings, arrays, choices, and user-defined structures. Its release cadence is primarily influenced by updates to the upstream `binary-parser` and the ongoing development of its unique encoding features, with an explicit long-term goal of merging these enhancements back into the main project.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a binary parser and encoder for an IP packet header, then parse a hex buffer and encode a JavaScript object back to binary.

import { Parser } from 'binary-parser-encoder';
import { Buffer } from 'buffer'; // Explicitly import Buffer for clarity/bundler compatibility

// Build an IP packet header Parser with encoding capabilities
const ipHeader = new Parser()
  .endianess("big")
  .bit4("version")
  .bit4("headerLength")
  .uint8("tos")
  .uint16("packetLength")
  .uint16("id")
  .bit3("offset")
  .bit13("fragOffset")
  .uint8("ttl")
  .uint8("protocol")
  .uint16("checksum")
  .array("src", {
    type: "uint8",
    length: 4
  })
  .array("dst", {
    type: "uint8",
    length: 4
  });

// Prepare buffer to parse.
const buf = Buffer.from("450002c5939900002c06ef98adc24f6c850186d1", "hex");

// Parse buffer and show result
console.log('Parsed IP Header:', ipHeader.parse(buf));

// Define an object to be encoded
const anIpHeader = {
  version: 4,
  headerLength: 5,
  tos: 0,
  packetLength: 709,
  id: 37785,
  offset: 0,
  fragOffset: 0,
  ttl: 44,
  protocol: 6,
  checksum: 61336,
  src: [ 173, 194, 79, 108 ],
  dst: [ 133, 1, 134, 209 ]
};

// Encode an IP header object and show result as hex string
console.log('Encoded IP Header (hex):', ipHeader.encode(anIpHeader).toString("hex"));

view raw JSON →