or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-types.mdexperimental.mdextended-json.mdindex.mdserialization.mdutilities.md
tile.json

tessl/npm-bson

A BSON (Binary JSON) parser for Node.js and browsers with comprehensive data type support and Extended JSON functionality

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/bson@6.10.x

To install, run

npx @tessl/cli install tessl/npm-bson@6.10.0

index.mddocs/

BSON

BSON (Binary JSON) is a comprehensive parser library that enables serialization and deserialization of JSON-like documents into a binary format. It provides complete BSON specification support with all data types including ObjectId, Binary, Decimal128, Long, Timestamp, and Extended JSON functionality for human-readable representation.

Package Information

  • Package Name: bson
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install bson

Core Imports

import { BSON, EJSON, ObjectId, serialize, deserialize } from "bson";

For CommonJS:

const { BSON, EJSON, ObjectId, serialize, deserialize } = require("bson");

Browser ES modules:

<script type="module">
  import { BSON, EJSON, ObjectId } from './lib/bson.mjs';
</script>

Basic Usage

import { serialize, deserialize, ObjectId, EJSON } from "bson";

// Create BSON data with ObjectId
const document = {
  _id: new ObjectId(),
  name: "John Doe",
  age: 30,
  active: true
};

// Serialize to binary format
const bytes = serialize(document);
console.log(bytes); // Uint8Array containing BSON data

// Deserialize back to JavaScript object
const restored = deserialize(bytes);
console.log(restored);

// Convert to Extended JSON for human-readable format
const ejsonString = EJSON.stringify(document);
console.log(ejsonString); // {"_id":{"$oid":"..."},"name":"John Doe","age":30,"active":true}

// Parse Extended JSON back to BSON objects
const parsed = EJSON.parse(ejsonString);

Architecture

BSON is built around several key components:

  • Core Serialization: Functions for converting between JavaScript objects and binary BSON format
  • BSON Data Types: Comprehensive set of BSON-specific types (ObjectId, Binary, Long, Decimal128, etc.)
  • Extended JSON: Human-readable JSON representation of BSON data with type preservation
  • Cross-Platform Compatibility: Optimized bundles for Node.js, browsers, and React Native
  • Utilities: Low-level byte manipulation and number handling utilities
  • Type Safety: Full TypeScript support with complete type definitions

Capabilities

Core Serialization

Binary serialization and deserialization functions for converting JavaScript objects to/from BSON format with configurable options.

function serialize(object: Document, options?: SerializeOptions): Uint8Array;
function deserialize(buffer: Uint8Array, options?: DeserializeOptions): Document;
function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number;

interface Document {
  [key: string]: any;
}

interface SerializeOptions {
  checkKeys?: boolean;
  serializeFunctions?: boolean;
  ignoreUndefined?: boolean;
  minInternalBufferSize?: number;
  index?: number;
}

interface DeserializeOptions {
  promoteBuffers?: boolean;
  promoteLongs?: boolean;
  promoteValues?: boolean;
  fieldsAsRaw?: Document;
  bsonRegExp?: boolean;
  allowObjectSmallerThanBufferSize?: boolean;
  index?: number;
  validation?: { utf8?: boolean | { [key: string]: boolean } };
  useBigInt64?: boolean;
}

Core Serialization

BSON Data Types

Complete set of BSON-specific data types including ObjectId, Binary, Long, Decimal128, Timestamp, and others with full type preservation and Extended JSON support.

class ObjectId {
  constructor(id?: string | number | ObjectId | ObjectIdLike | Uint8Array);
  toHexString(): string;
  static createFromTime(timestamp: number): ObjectId;
  static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean;
}

class Binary {
  constructor(buffer?: BinarySequence, subType?: number);
  static readonly SUBTYPE_DEFAULT: 0;
  static readonly SUBTYPE_UUID: 4;
  value(asRaw?: boolean): string | Uint8Array;
}

class Long {
  constructor(low?: number | bigint | string, high?: number | boolean, unsigned?: boolean);
  static fromString(str: string, unsigned?: boolean | number, radix?: number): Long;
  toNumber(): number;
  toBigInt(): bigint;
}

BSON Data Types

Extended JSON (EJSON)

Extended JSON functionality for converting BSON data to/from human-readable JSON format while preserving type information.

namespace EJSON {
  function parse(text: string, options?: EJSONOptions): any;
  function stringify(value: any, replacer?: Function | Array, space?: string | number, options?: EJSONOptions): string;
  function serialize(bson: any, options?: EJSONOptions): any;
  function deserialize(ejson: any, options?: EJSONOptions): any;
}

interface EJSONOptions {
  legacy?: boolean;
  relaxed?: boolean;
  useBigInt64?: boolean;
}

Extended JSON

Utilities and Error Handling

Cross-platform utilities for byte manipulation, number handling, and comprehensive error handling with specific error types.

class BSONError extends Error {
  static isBSONError(value: unknown): value is BSONError;
}

class ByteUtils {
  static allocate(size: number): Uint8Array;
  static toBase64(buffer: Uint8Array): string;
  static fromBase64(base64: string): Uint8Array;
  static toHex(buffer: Uint8Array): string;
  static fromHex(hex: string): Uint8Array;
}

class NumberUtils {
  static getInt32LE(source: Uint8Array, offset: number): number;
  static getBigInt64LE(source: Uint8Array, offset: number): bigint;
  static setInt32LE(destination: Uint8Array, offset: number, value: number): 4;
}

Utilities and Error Handling

Experimental APIs

Experimental low-level parsing utilities for advanced use cases requiring direct BSON element access.

namespace onDemand {
  function parseToElements(bytes: Uint8Array, startOffset?: number): Iterable<BSONElement>;
  const ByteUtils: ByteUtils;
  const NumberUtils: NumberUtils;
}

interface BSONElement {
  type: number;
  name: string;
  offset: number;
  length: number;
}

Experimental APIs

Types

type BinarySequence = Uint8Array | number[];

interface ObjectIdLike {
  id: string | Uint8Array;
  toHexString(): string;
}

interface ObjectIdExtended {
  $oid: string;
}

interface BinaryExtended {
  $binary: {
    subType: string;
    base64: string;
  };
}

interface LongExtended {
  $numberLong: string;
}

interface Decimal128Extended {
  $numberDecimal: string;
}

interface TimestampExtended {
  $timestamp: {
    t: number;
    i: number;
  };
}

interface DoubleExtended {
  $numberDouble: string;
}

interface Int32Extended {
  $numberInt: string;
}

interface BSONRegExpExtended {
  $regularExpression: {
    pattern: string;
    options: string;
  };
}

interface DBRefLike {
  $ref: string;
  $id: ObjectId;
  $db?: string;
}

enum BSONType {
  double = 1,
  string = 2,
  object = 3,
  array = 4,
  binData = 5,
  undefined = 6,
  objectId = 7,
  bool = 8,
  date = 9,
  null = 10,
  regex = 11,
  dbPointer = 12,
  javascript = 13,
  symbol = 14,
  javascriptWithScope = 15,
  int = 16,
  timestamp = 17,
  long = 18,
  decimal = 19,
  minKey = -1,
  maxKey = 127
}