bson
A bson parser for node.js and the browser
Last updated 4 months ago by mbroadst .
Apache-2.0 · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install bson 
SYNC missed versions from official npm registry.

BSON parser

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.

This browser version of the BSON parser is compiled using rollup and the current version is pre-compiled in the dist directory.

This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at mongod-js/bson-ext.

Table of Contents

Bugs / Feature Requests

Think you've found a bug? Want to see a new feature in bson? Please open a case in our issue management tool, JIRA:

  1. Create an account and login: jira.mongodb.org
  2. Navigate to the NODE project: jira.mongodb.org/browse/NODE
  3. Click Create Issue - Please provide as much information as possible about the issue and how to reproduce it.

Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are public.

Usage

To build a new version perform the following operations:

npm install
npm run build

Node (no bundling)

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

const BSON = require('bson');
const Long = BSON.Long;

// Serialize a document
const doc = { long: Long.fromNumber(100) };
const data = BSON.serialize(doc);
console.log('data:', data);

// Deserialize the resulting Buffer
const doc_2 = BSON.deserialize(data);
console.log('doc_2:', doc_2);

Browser (no bundling)

If you are not using a bundler like webpack, you can include dist/bson.bundle.js using a script tag. It includes polyfills for built-in node types like Buffer.

<script src="./dist/bson.bundle.js"></script>

<script>
  function start() {
    // Get the Long type
    const Long = BSON.Long;

    // Serialize a document
    const doc = { long: Long.fromNumber(100) }
    const data = BSON.serialize(doc);
    console.log('data:', data);

    // De serialize it again
    const doc_2 = BSON.deserialize(data);
    console.log('doc_2:', doc_2);
  }
</script>

Using webpack

If using webpack, you can use your normal import/require syntax of your project to pull in the bson library.

ES6 Example:

import { Long, serialize, deserialize } from 'bson';

// Serialize a document
const doc = { long: Long.fromNumber(100) };
const data = serialize(doc);
console.log('data:', data);

// De serialize it again
const doc_2 = deserialize(data);
console.log('doc_2:', doc_2);

ES5 Example:

const BSON = require('bson');
const Long = BSON.Long;

// Serialize a document
const doc = { long: Long.fromNumber(100) };
const data = BSON.serialize(doc);
console.log('data:', data);

// Deserialize the resulting Buffer
const doc_2 = BSON.deserialize(data);
console.log('doc_2:', doc_2);

Depending on your settings, webpack will under the hood resolve to one of the following:

  • dist/bson.browser.esm.js If your project is in the browser and using ES6 modules (Default for webworker and web targets)
  • dist/bson.browser.umd.js If your project is in the browser and not using ES6 modules
  • dist/bson.esm.js If your project is in Node.js and using ES6 modules (Default for node targets)
  • lib/bson.js (the normal include path) If your project is in Node.js and not using ES6 modules

For more information, see this page on webpack's resolve.mainFields and the package.json for this project

Usage with Angular

Starting with Angular 6, Angular CLI removed the shim for global and other node built-in variables (original comment here). If you are using BSON with Angular, you may need to add the following shim to your polyfills.ts file:

// In polyfills.ts
(window as any).global = window;

Installation

npm install bson

Documentation

Objects

EJSON : object

Functions

setInternalBufferSize(size)

Sets the size of the internal serialization buffer.

serialize(object)Buffer

Serialize a Javascript object.

serializeWithBufferAndIndex(object, buffer)Number

Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.

deserialize(buffer)Object

Deserialize data as BSON.

calculateObjectSize(object)Number

Calculate the bson size for a passed in Javascript object.

deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options])Number

Deserialize stream data as BSON documents.

EJSON

EJSON.parse(text, [options])

Param Type Default Description
text string
[options] object Optional settings
[options.relaxed] boolean true Attempt to return native JS types where possible, rather than BSON types (if true)

Parse an Extended JSON string, constructing the JavaScript value or object described by that string.

Example

const { EJSON } = require('bson');
const text = '{ "int32": { "$numberInt": "10" } }';

// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
console.log(EJSON.parse(text, { relaxed: false }));

// prints { int32: 10 }
console.log(EJSON.parse(text));

EJSON.stringify(value, [replacer], [space], [options])

Param Type Default Description
value object The value to convert to extended JSON
[replacer] function | array A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
[space] string | number A String or Number object that's used to insert white space into the output JSON string for readability purposes.
[options] object Optional settings
[options.relaxed] boolean true Enabled Extended JSON's relaxed mode
[options.legacy] boolean true Output in Extended JSON v1

Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Example

const { EJSON } = require('bson');
const Int32 = require('mongodb').Int32;
const doc = { int32: new Int32(10) };

// prints '{"int32":{"$numberInt":"10"}}'
console.log(EJSON.stringify(doc, { relaxed: false }));

// prints '{"int32":10}'
console.log(EJSON.stringify(doc));

EJSON.serialize(bson, [options])

Param Type Description
bson object The object to serialize
[options] object Optional settings passed to the stringify function

Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.

EJSON.deserialize(ejson, [options])

Param Type Description
ejson object The Extended JSON object to deserialize
[options] object Optional settings passed to the parse method

Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types

setInternalBufferSize(size)

Param Type Description
size number The desired size for the internal serialization buffer

Sets the size of the internal serialization buffer.

serialize(object)

Param Type Default Description
object Object the Javascript object to serialize.
[options.checkKeys] Boolean the serializer will check if keys are valid.
[options.serializeFunctions] Boolean false serialize the javascript functions (default:false).
[options.ignoreUndefined] Boolean true ignore undefined fields (default:true).

Serialize a Javascript object.

Returns: Buffer - returns the Buffer object containing the serialized object.

serializeWithBufferAndIndex(object, buffer)

Param Type Default Description
object Object the Javascript object to serialize.
buffer Buffer the Buffer you pre-allocated to store the serialized BSON object.
[options.checkKeys] Boolean the serializer will check if keys are valid.
[options.serializeFunctions] Boolean false serialize the javascript functions (default:false).
[options.ignoreUndefined] Boolean true ignore undefined fields (default:true).
[options.index] Number the index in the buffer where we wish to start serializing into.

Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.

Returns: Number - returns the index pointing to the last written byte in the buffer.

deserialize(buffer)

Param Type Default Description
buffer Buffer the buffer containing the serialized set of BSON documents.
[options.evalFunctions] Object false evaluate functions in the BSON document scoped to the object deserialized.
[options.cacheFunctions] Object false cache evaluated functions for reuse.
[options.cacheFunctionsCrc32] Object false use a crc32 code for caching, otherwise use the string of the function.
[options.promoteLongs] Object true when deserializing a Long will fit it into a Number if it's smaller than 53 bits
[options.promoteBuffers] Object false when deserializing a Binary will return it as a node.js Buffer instance.
[options.promoteValues] Object false when deserializing will promote BSON values to their Node.js closest equivalent types.
[options.fieldsAsRaw] Object allow to specify if there what fields we wish to return as unserialized raw buffer.
[options.bsonRegExp] Object false return BSON regular expressions as BSONRegExp instances.
[options.allowObjectSmallerThanBufferSize] boolean false allows the buffer to be larger than the parsed BSON object

Deserialize data as BSON.

Returns: Object - returns the deserialized Javascript Object.

calculateObjectSize(object)

Param Type Default Description
object Object the Javascript object to calculate the BSON byte size for.
[options.serializeFunctions] Boolean false serialize the javascript functions (default:false).
[options.ignoreUndefined] Boolean true ignore undefined fields (default:true).

Calculate the bson size for a passed in Javascript object.

Returns: Number - returns the number of bytes the BSON object will take up.

deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options])

Param Type Default Description
data Buffer the buffer containing the serialized set of BSON documents.
startIndex Number the start index in the data Buffer where the deserialization is to start.
numberOfDocuments Number number of documents to deserialize.
documents Array an array where to store the deserialized documents.
docStartIndex Number the index in the documents array from where to start inserting documents.
[options] Object additional options used for the deserialization.
[options.evalFunctions] Object false evaluate functions in the BSON document scoped to the object deserialized.
[options.cacheFunctions] Object false cache evaluated functions for reuse.
[options.cacheFunctionsCrc32] Object false use a crc32 code for caching, otherwise use the string of the function.
[options.promoteLongs] Object true when deserializing a Long will fit it into a Number if it's smaller than 53 bits
[options.promoteBuffers] Object false when deserializing a Binary will return it as a node.js Buffer instance.
[options.promoteValues] Object false when deserializing will promote BSON values to their Node.js closest equivalent types.
[options.fieldsAsRaw] Object allow to specify if there what fields we wish to return as unserialized raw buffer.
[options.bsonRegExp] Object false return BSON regular expressions as BSONRegExp instances.

Deserialize stream data as BSON documents.

Returns: Number - returns the next index in the buffer after deserialization x numbers of documents.

FAQ

Why does undefined get converted to null?

The undefined BSON type has been deprecated for many years, so this library has dropped support for it. Use the ignoreUndefined option (for example, from the driver ) to instead remove undefined keys.

How do I add custom serialization logic?

This library looks for toBSON() functions on every path, and calls the toBSON() function to get the value to serialize.

const BSON = require('bson');

class CustomSerialize {
  toBSON() {
    return 42;
  }
}

const obj = { answer: new CustomSerialize() };
// "{ answer: 42 }"
console.log(BSON.deserialize(BSON.serialize(obj)));

Current Tags

  • 4.0.4                                ...           latest (4 months ago)
  • 1.1.4                                ...           stable (4 months ago)

114 Versions

  • 4.0.4                                ...           4 months ago
  • 1.1.4                                ...           4 months ago
  • 4.0.3                                ...           6 months ago
  • 1.1.3 [deprecated]           ...           8 months ago
  • 1.1.2 [deprecated]           ...           8 months ago
  • 1.1.1 [deprecated]           ...           a year ago
  • 4.0.2                                ...           a year ago
  • 4.0.1                                ...           2 years ago
  • 4.0.0                                ...           2 years ago
  • 4.0.0-rc8                                ...           2 years ago
  • 4.0.0-rc7                                ...           2 years ago
  • 4.0.0-rc6                                ...           2 years ago
  • 4.0.0-rc5                                ...           2 years ago
  • 4.0.0-rc4                                ...           2 years ago
  • 4.0.0-rc3                                ...           2 years ago
  • 4.0.0-rc2                                ...           2 years ago
  • 4.0.0-rc1                                ...           2 years ago
  • 1.1.0 [deprecated]           ...           2 years ago
  • 3.0.2 [deprecated]           ...           2 years ago
  • 3.0.1 [deprecated]           ...           2 years ago
  • 3.0.0 [deprecated]           ...           2 years ago
  • 1.0.9 [deprecated]           ...           2 years ago
  • 1.0.8 [deprecated]           ...           2 years ago
  • 2.0.8 [deprecated]           ...           2 years ago
  • 1.0.7 [deprecated]           ...           2 years ago
  • 2.0.7 [deprecated]           ...           2 years ago
  • 2.0.6 [deprecated]           ...           2 years ago
  • 2.0.5 [deprecated]           ...           2 years ago
  • 2.0.4 [deprecated]           ...           2 years ago
  • 2.0.3 [deprecated]           ...           2 years ago
  • 1.0.6 [deprecated]           ...           2 years ago
  • 2.0.2 [deprecated]           ...           2 years ago
  • 2.0.1 [deprecated]           ...           2 years ago
  • 1.0.5 [deprecated]           ...           2 years ago
  • 2.0.0 [deprecated]           ...           2 years ago
  • 1.0.4 [deprecated]           ...           4 years ago
  • 1.0.3 [deprecated]           ...           4 years ago
  • 1.0.2 [deprecated]           ...           4 years ago
  • 1.0.1 [deprecated]           ...           4 years ago
  • 1.0.0 [deprecated]           ...           4 years ago
  • 0.5.7 [deprecated]           ...           4 years ago
  • 0.5.6 [deprecated]           ...           4 years ago
  • 0.5.5 [deprecated]           ...           4 years ago
  • 0.5.4 [deprecated]           ...           4 years ago
  • 0.5.3 [deprecated]           ...           4 years ago
  • 0.5.2 [deprecated]           ...           4 years ago
  • 0.5.1 [deprecated]           ...           4 years ago
  • 0.5.0 [deprecated]           ...           4 years ago
  • 0.4.23 [deprecated]           ...           4 years ago
  • 0.4.22 [deprecated]           ...           4 years ago
  • 0.4.21 [deprecated]           ...           5 years ago
  • 0.4.20 [deprecated]           ...           5 years ago
  • 0.4.19 [deprecated]           ...           5 years ago
  • 0.4.18 [deprecated]           ...           5 years ago
  • 0.4.17 [deprecated]           ...           5 years ago
  • 0.4.16 [deprecated]           ...           5 years ago
  • 0.4.15 [deprecated]           ...           5 years ago
  • 0.4.14 [deprecated]           ...           5 years ago
  • 0.4.13 [deprecated]           ...           5 years ago
  • 0.4.12 [deprecated]           ...           5 years ago
  • 0.4.10 [deprecated]           ...           5 years ago
  • 0.2.22 [deprecated]           ...           5 years ago
  • 0.4.8 [deprecated]           ...           5 years ago
  • 0.4.7 [deprecated]           ...           5 years ago
  • 0.4.6 [deprecated]           ...           5 years ago
  • 0.4.5 [deprecated]           ...           5 years ago
  • 0.4.4 [deprecated]           ...           5 years ago
  • 0.4.3 [deprecated]           ...           5 years ago
  • 0.4.2 [deprecated]           ...           5 years ago
  • 0.4.1 [deprecated]           ...           5 years ago
  • 0.4.0 [deprecated]           ...           5 years ago
  • 0.3.2 [deprecated]           ...           5 years ago
  • 0.3.1 [deprecated]           ...           5 years ago
  • 0.3.0 [deprecated]           ...           5 years ago
  • 0.2.21 [deprecated]           ...           5 years ago
  • 0.2.20 [deprecated]           ...           5 years ago
  • 0.2.19 [deprecated]           ...           5 years ago
  • 0.2.18 [deprecated]           ...           5 years ago
  • 0.2.17 [deprecated]           ...           5 years ago
  • 0.2.16 [deprecated]           ...           6 years ago
  • 0.2.15 [deprecated]           ...           6 years ago
  • 0.2.14 [deprecated]           ...           6 years ago
  • 0.2.13 [deprecated]           ...           6 years ago
  • 0.2.12 [deprecated]           ...           6 years ago
  • 0.2.11 [deprecated]           ...           6 years ago
  • 0.2.10 [deprecated]           ...           6 years ago
  • 0.2.9 [deprecated]           ...           6 years ago
  • 0.2.8 [deprecated]           ...           6 years ago
  • 0.2.7 [deprecated]           ...           6 years ago
  • 0.2.6 [deprecated]           ...           6 years ago
  • 0.2.5 [deprecated]           ...           7 years ago
  • 0.2.4 [deprecated]           ...           7 years ago
  • 0.2.3 [deprecated]           ...           7 years ago
  • 0.2.2 [deprecated]           ...           7 years ago
  • 0.2.1 [deprecated]           ...           7 years ago
  • 0.2.0 [deprecated]           ...           7 years ago
  • 0.1.9 [deprecated]           ...           7 years ago
  • 0.1.8 [deprecated]           ...           7 years ago
  • 0.1.7 [deprecated]           ...           7 years ago
  • 0.1.6 [deprecated]           ...           7 years ago
  • 0.1.5 [deprecated]           ...           8 years ago
  • 0.1.4 [deprecated]           ...           8 years ago
  • 0.1.3 [deprecated]           ...           8 years ago
  • 0.1.1 [deprecated]           ...           8 years ago
  • 0.1.0 [deprecated]           ...           8 years ago
  • 0.0.9 [deprecated]           ...           8 years ago
  • 0.0.8 [deprecated]           ...           8 years ago
  • 0.0.7 [deprecated]           ...           8 years ago
  • 0.0.6 [deprecated]           ...           8 years ago
  • 0.0.5 [deprecated]           ...           8 years ago
  • 0.0.4 [deprecated]           ...           8 years ago
  • 0.0.3 [deprecated]           ...           9 years ago
  • 0.0.2 [deprecated]           ...           9 years ago
  • 0.0.1 [deprecated]           ...           9 years ago
Downloads
Today 1,030
This Week 1,030
This Month 38,692
Last Day 1,291
Last Week 19,332
Last Month 75,467
Dependencies (2)
Dependents (649)

Copyright 2014 - 2016 © taobao.org |