Home

Awesome

BSON parser

BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in the specification.

This module is a C++ addon for Node.js that implements the BSON parsing and serialization outside of the JavaScript environment in order to increase speed and memory efficiency for certain workloads. It uses the same types as the pure JavaScript implementation, which can be found at mongodb/js-bson.

Usage

To build a new version perform the following operation.

npm install
npm run build

A simple example of how to use BSON in Node.js:

// Get BSON parser class
var BSON = require('bson-ext')
// Get the Long type
var Long = BSON.Long;
// Create a bson parser instance, passing in all the types
// This is needed so the C++ parser has references to the classes and can
// use them to serialize and deserialize the types.
var bson = new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]);

// Serialize document
var doc = { long: Long.fromNumber(100) }

// Serialize a document
var data = bson.serialize(doc)
console.log('data:', data)

// Deserialize the resulting Buffer
var doc_2 = bson.deserialize(data)
console.log('doc_2:', doc_2)

Installation

npm install bson-ext

API

BSON types

For all BSON types documentation, please refer to the documentation for the MongoDB Node.js driver.

BSON serialization and deserialiation

new BSON() - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON.

BSON.serialize

The BSON serialize method takes a JavaScript object and an optional options object and returns a Node.js 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.

BSON.calculateObjectSize

The BSON calculateObjectSize method takes a JavaScript object and an optional options object and returns the size of the BSON object.

BSON.deserialize

The BSON deserialize method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object.

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.