Binary Parser and Encoder
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
-
TypeError: Parser is not a constructor
cause This error typically occurs when attempting to import the `Parser` class using an incorrect syntax, such as `const Parser = require('binary-parser-encoder');` (CommonJS) or `import Parser from 'binary-parser-encoder';` (ESM default import). The `Parser` class is a named export.fixFor CommonJS, use `const { Parser } = require('binary-parser-encoder');`. For ESM, use `import { Parser } from 'binary-parser-encoder';`. -
TypeError: ipHeader.encode is not a function
cause This runtime error indicates that you have likely installed or are importing the `Parser` class from the original `binary-parser` package, which does not include the `encode` method, instead of `binary-parser-encoder`.fixVerify your `package.json` to ensure `binary-parser-encoder` is installed. Double-check your import statements to confirm that you are importing `Parser` specifically from `binary-parser-encoder`. -
Property 'encode' does not exist on type 'Parser<any>'. Did you mean 'parse'?
cause In a TypeScript project, this type error suggests that the TypeScript compiler is using type definitions from the original `binary-parser` package, even if you have `binary-parser-encoder` installed. This can result from conflicting `@types/` packages or incorrect module resolution.fixEnsure that `@types/binary-parser` is not installed if you are exclusively using `binary-parser-encoder`. This package ships its own type definitions, which correctly include the `encode` method. Restart your TypeScript language server or IDE after making dependency changes.
Warnings
- gotcha This package is a fork of the original `binary-parser` library. It specifically adds an `encode` feature not present in the upstream project. Developers migrating from or expecting the exact behavior of `binary-parser` should be aware of this distinction and potential API differences.
- breaking Version 1.5.2 introduced a migration of the codebase to TypeScript. While largely designed for compatibility, this change might lead to stricter type checking, subtle differences in type inference, or require minor adjustments in existing TypeScript projects. Pure JavaScript projects might also be affected depending on their build toolchain.
- gotcha The `encode()` method is a core and unique feature of `binary-parser-encoder` and is not available in the original `binary-parser` package. Attempting to call `encode()` on a `Parser` instance imported from `binary-parser` will result in a runtime `TypeError`.
- gotcha The `new Parser([options])` constructor accepts an optional `smartBufferSize` option, which primarily controls the chunk size of the internal buffer used during encoding. This option is specific to the encoding feature and does not impact parsing operations.
Install
-
npm install binary-parser-encoder -
yarn add binary-parser-encoder -
pnpm add binary-parser-encoder
Imports
- Parser
import Parser from 'binary-parser-encoder'; // OR const Parser = require('binary-parser-encoder');import { Parser } from 'binary-parser-encoder'; - Parser (CommonJS)
const Parser = require('binary-parser-encoder');const { Parser } = require('binary-parser-encoder'); - Parser (Type Import)
import type { Parser } from 'binary-parser-encoder';
Quickstart
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"));