BSON-EXT
A BSON parser Node.JS native addon.
BSON is short for Binary JSON and is the binary-encoded serialization of JSON-like documents. You can learn more about it in the specification.
While this library is compatible with the mongodb driver version 4+, bson-ext will soon be deprecated and no longer supported. It is strongly recommended
that js-bson be used instead.
NOTE: bson-ext version 4+ works with js-bson version 4+ and the mongodb driver version 4+.
Installation
npm install bson-ext
Usage
A simple example of how to use BSON in Node.js
:
const BSON = require('bson-ext')
const Long = BSON.Long;
const doc = { long: Long.fromNumber(100) }
const data = BSON.serialize(doc)
console.log('data:', data)
var docRoundTrip = bson.deserialize(data)
console.log('docRoundTrip:', docRoundTrip)
Compiling
To build a new version perform the following operation.
npm install
npm run build
API
BSON types
For all BSON types documentation, please refer to the documentation for the MongoDB Node.js driver.
BSON.serialize
The BSON serialize
method takes a JavaScript object and an optional options object and returns a Node.js Buffer.
interface Document {
[key: string]: any;
}
interface SerializeOptions {
checkKeys?: boolean;
serializeFunctions?: boolean;
ignoreUndefined?: boolean;
}
function serialize(object: Document, options?: SerializeOptions): Buffer;
BSON.serializeWithBufferAndIndex
The BSON serializeWithBufferAndIndex
method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer.
function serializeWithBufferAndIndex(object: Document, finalBuffer: Buffer, options?: SerializeOptions): number;
BSON.calculateObjectSize
The BSON calculateObjectSize
method takes a JavaScript object and an optional options object and returns the size of the BSON object.
interface CalculateObjectSizeOptions {
serializeFunctions?: boolean;
ignoreUndefined?: boolean;
}
function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number;
BSON.deserialize
The BSON deserialize
method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object.
interface DeserializeOptions {
evalFunctions?: boolean;
cacheFunctions?: boolean;
promoteLongs?: boolean;
promoteBuffers?: boolean;
promoteValues?: boolean;
fieldsAsRaw?: Document;
bsonRegExp?: boolean;
allowObjectSmallerThanBufferSize?: boolean;
index?: number;
}
function deserialize(buffer: Buffer | ArrayBufferView | ArrayBuffer, options?: DeserializeOptions): Document;
BSON.deserializeStream
The BSON deserializeStream
method takes a Node.js Buffer, startIndex
and allow more control over deserialization of a Buffer containing concatenated BSON documents.
function deserializeStream(data: Buffer | ArrayBufferView | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number;