PBF: Low-Level Protocol Buffers for JavaScript

4.0.1 · active · verified Sun Apr 19

PBF is a low-level, fast, and ultra-lightweight JavaScript library (3KB gzipped) for efficiently decoding and encoding Protocol Buffers (protobuf), a compact binary format for structured data serialization. Version 4.0.1 is the current stable release, which includes minor fixes building upon the significant 4.0.0 overhaul. The library is actively maintained, with a recent major release focusing on modernizing the codebase and developer experience. A key differentiator of PBF is its exceptional performance, consistently outperforming `JSON.parse`/`JSON.stringify` and other protobuf implementations like `protocol-buffers` in benchmarks. It supports lazy decoding and offers extensive customization options for reading and writing data, making it suitable for both Node.js and browser environments where performance and bundle size are critical considerations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates manual encoding and decoding of a custom data structure using PBF's low-level API without a .proto schema, showcasing its `writeField`, `readField`, and `readMessage` methods.

import Pbf from 'pbf';

interface MyComplexData {
  name: string;
  version: number;
  layer: {
    name: string;
    size: number;
  };
}

function writeLayer(layer: MyComplexData['layer'], pbf: Pbf) {
  pbf.writeStringField(1, layer.name);
  pbf.writeVarintField(3, layer.size);
}

function writeData(data: MyComplexData, pbf: Pbf) {
  pbf.writeStringField(1, data.name);
  pbf.writeVarintField(2, data.version);
  pbf.writeMessage(3, writeLayer, data.layer);
}

function readLayer(tag: number, layer: MyComplexData['layer'], pbf: Pbf) {
  if (tag === 1) layer.name = pbf.readString();
  else if (tag === 3) layer.size = pbf.readVarint();
}

function readData(tag: number, data: MyComplexData, pbf: Pbf) {
  if (tag === 1) data.name = pbf.readString();
  else if (tag === 2) data.version = pbf.readVarint();
  else if (tag === 3) data.layer = pbf.readMessage(readLayer, {} as MyComplexData['layer']);
}

const myData: MyComplexData = {
  name: 'TelemetryPacket',
  version: 42,
  layer: {
    name: 'SensorReadings',
    size: 1024
  }
};

const pbfWriter = new Pbf();
writeData(myData, pbfWriter);
const encodedBuffer: Uint8Array = pbfWriter.finish();

console.log('Encoded buffer (Uint8Array):', encodedBuffer);
console.log('Encoded buffer length:', encodedBuffer.length, 'bytes');

const pbfReader = new Pbf(encodedBuffer);
const decodedData: MyComplexData = pbfReader.readFields(readData, {} as MyComplexData);

console.log('Decoded data:', decodedData);

view raw JSON →