A BSON (Binary JSON) parser for Node.js and browsers with comprehensive data type support and Extended JSON functionality
npx @tessl/cli install tessl/npm-bson@6.10.0BSON (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.
npm install bsonimport { 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>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);BSON is built around several key components:
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;
}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;
}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;
}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;
}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;
}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
}