{"id":11532,"library":"pbf","title":"PBF: Low-Level Protocol Buffers for JavaScript","description":"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.","status":"active","version":"4.0.1","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/mapbox/pbf","tags":["javascript","protocol","buffer","pbf","protobuf","binary","format","serialization","encoder","typescript"],"install":[{"cmd":"npm install pbf","lang":"bash","label":"npm"},{"cmd":"yarn add pbf","lang":"bash","label":"yarn"},{"cmd":"pnpm add pbf","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Since v4.0.0, PBF is an ES module and should be imported using ES module syntax. Direct CommonJS `require()` is no longer supported.","wrong":"const Pbf = require('pbf');","symbol":"Pbf","correct":"import Pbf from 'pbf';"},{"note":"PBF's code generation (CLI tool) defaults to ES modules since v4.0.0. Generated files use named exports and should be imported with ES module syntax. The `--legacy` flag is required for CommonJS output.","wrong":"const { readMyMessage, writeMyMessage } = require('./my-schema');","symbol":"{ readMyMessage, writeMyMessage } (generated code)","correct":"import { readMyMessage, writeMyMessage } from './my-schema.js';"},{"note":"The `compile` utility for runtime schema compilation is also an ES module and should be imported directly from its subpath using ES module syntax.","wrong":"const { compile } = require('pbf/compile');","symbol":"compile","correct":"import { compile } from 'pbf/compile';"}],"quickstart":{"code":"import Pbf from 'pbf';\n\ninterface MyComplexData {\n  name: string;\n  version: number;\n  layer: {\n    name: string;\n    size: number;\n  };\n}\n\nfunction writeLayer(layer: MyComplexData['layer'], pbf: Pbf) {\n  pbf.writeStringField(1, layer.name);\n  pbf.writeVarintField(3, layer.size);\n}\n\nfunction writeData(data: MyComplexData, pbf: Pbf) {\n  pbf.writeStringField(1, data.name);\n  pbf.writeVarintField(2, data.version);\n  pbf.writeMessage(3, writeLayer, data.layer);\n}\n\nfunction readLayer(tag: number, layer: MyComplexData['layer'], pbf: Pbf) {\n  if (tag === 1) layer.name = pbf.readString();\n  else if (tag === 3) layer.size = pbf.readVarint();\n}\n\nfunction readData(tag: number, data: MyComplexData, pbf: Pbf) {\n  if (tag === 1) data.name = pbf.readString();\n  else if (tag === 2) data.version = pbf.readVarint();\n  else if (tag === 3) data.layer = pbf.readMessage(readLayer, {} as MyComplexData['layer']);\n}\n\nconst myData: MyComplexData = {\n  name: 'TelemetryPacket',\n  version: 42,\n  layer: {\n    name: 'SensorReadings',\n    size: 1024\n  }\n};\n\nconst pbfWriter = new Pbf();\nwriteData(myData, pbfWriter);\nconst encodedBuffer: Uint8Array = pbfWriter.finish();\n\nconsole.log('Encoded buffer (Uint8Array):', encodedBuffer);\nconsole.log('Encoded buffer length:', encodedBuffer.length, 'bytes');\n\nconst pbfReader = new Pbf(encodedBuffer);\nconst decodedData: MyComplexData = pbfReader.readFields(readData, {} as MyComplexData);\n\nconsole.log('Decoded data:', decodedData);\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Refactor your codebase to use ES module `import` and `export` syntax. If targeting environments that do not support ESM natively, use a transpiler like Babel or webpack.","message":"PBF v4.0.0 completely dropped CommonJS support and is now exclusively distributed as an ES module. Direct `require()` statements will fail.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Ensure your target runtime environment supports modern ES syntax or integrate a transpilation step (e.g., Babel) into your build process to downlevel the code.","message":"The underlying codebase was rewritten to use modern ES syntax in v4.0.0. While this improves maintainability and performance, it might break compatibility with very old JavaScript environments (e.g., Internet Explorer 11) that lack support for these features.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Update your build scripts to handle ES module output (e.g., change `require` to `import` in generated files, or use bundlers). If CommonJS output is strictly required for generated code, use the `--legacy` flag when running the `pbf` CLI tool: `pbf --legacy example.proto > example.js`.","message":"PBF's CLI tool for generating JavaScript modules from `.proto` files now outputs ES modules by default since v4.0.0. Previously generated CommonJS modules are incompatible with this new default.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Adjust your import statements and code logic to use the new flat export structure for generated read and write functions. For example, change `read.MyMessage(pbf)` to `readMyMessage(pbf)`.","message":"Code generation in v4.0.0 was overhauled to produce simpler, more compact code with flat exports of read and write functions, rather than nested objects (e.g., `read.Example` vs `readExample`).","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Update to PBF v4.0.1 or higher to get the corrected typings, which mark the `buf` parameter as optional.","message":"The `Pbf` constructor's `buf` argument was incorrectly typed as mandatory in versions prior to 4.0.1, despite being optional in practice. This could lead to TypeScript errors when instantiating `new Pbf()` without arguments.","severity":"gotcha","affected_versions":">=4.0.0 <4.0.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change `const Pbf = require('pbf');` to `import Pbf from 'pbf';`. For generated code, change `const { readMyMessage } = require('./my-schema');` to `import { readMyMessage } from './my-schema.js';`.","cause":"Attempting to use `require()` to import PBF or code generated by PBF in an environment configured for ES modules, or in PBF v4+ which is ESM-only.","error":"ReferenceError: require is not defined"},{"fix":"Ensure your project is configured for ES modules and use `import Pbf from 'pbf';`. If using TypeScript, check `tsconfig.json` for `\"esModuleInterop\": true` and `\"module\": \"NodeNext\"` or `\"ES2020\"`.","cause":"This error often occurs when an ES module that uses a default export (like PBF v4) is incorrectly imported in a CommonJS context that doesn't properly handle `default` properties, or when a bundler/transpiler misinterprets the import.","error":"TypeError: pbf_1.default is not a constructor"},{"fix":"Review your import statements for generated code. Instead of `import { read } from './my-schema.js'; read.MyMessage(pbf);`, use `import { readMyMessage } from './my-schema.js'; readMyMessage(pbf);`.","cause":"This typically indicates that generated read/write functions are being accessed incorrectly after the v4.0.0 code generation overhaul, which flattened exports from nested objects.","error":"TypeError: Cannot read properties of undefined (reading 'readMyMessage')"}],"ecosystem":"npm"}