Socket
Socket
Sign inDemoInstall

bson

Package Overview
Dependencies
4
Maintainers
4
Versions
162
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    bson

A bson parser for node.js and the browser


Version published
Weekly downloads
5.6M
increased by3.71%
Maintainers
4
Install size
1.16 MB
Created
Weekly downloads
 

Package description

What is bson?

The bson npm package is a library that allows you to serialize and deserialize data in BSON format. BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. It is designed to be efficient in both storage space and scan-speed. The bson package is commonly used when working with MongoDB, as MongoDB uses BSON as its document storage format.

What are bson's main functionalities?

Serialization

This feature allows you to convert a JavaScript object into a BSON formatted buffer. This is useful for storing and transmitting data in a compact binary form.

{"const BSON = require('bson'); const bson = new BSON(); const doc = { hello: 'world' }; const data = bson.serialize(doc); console.log(data); // <Buffer 16 00 00 00 02 68 65 6c 6c 6f 00 06 00 00 00 77 6f 72 6c 64 00 00>"}

Deserialization

This feature allows you to convert BSON data back into a JavaScript object. This is useful when you need to read data that was stored or transmitted in BSON format.

{"const BSON = require('bson'); const bson = new BSON(); const data = Buffer.from('160000000268656c6c6f0006000000776f726c640000', 'hex'); const doc = bson.deserialize(data); console.log(doc); // { hello: 'world' }"}

Other packages similar to bson

Readme

Source

BSON parser

NOTE: This is usage documentation for the current 4.0.0 beta. You can find documentation for the 3.0 version of js-bson here

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 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

A simple example of how to use BSON in the browser:

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

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

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

    // Serialize a document
    const data = BSON.serialize(doc)
    // De serialize it again
    const doc_2 = BSON.deserialize(data)
  }
</script>

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

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

const doc = { long: Long.fromNumber(100) };

// Serialize a document
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);

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])
ParamTypeDefaultDescription
textstring
[options]objectOptional settings
[options.relaxed]booleantrueAttempt 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])
ParamTypeDefaultDescription
valueobjectThe value to convert to extended JSON
[replacer]function | arrayA 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 | numberA String or Number object that's used to insert white space into the output JSON string for readability purposes.
[options]objectOptional settings
[options.relaxed]booleantrueEnabled Extended JSON's relaxed mode

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])
ParamTypeDescription
bsonobjectThe object to serialize
[options]objectOptional 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])
ParamTypeDescription
ejsonobjectThe Extended JSON object to deserialize
[options]objectOptional settings passed to the parse method

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

setInternalBufferSize(size)

ParamTypeDescription
sizenumberThe desired size for the internal serialization buffer

Sets the size of the internal serialization buffer.

serialize(object)

ParamTypeDefaultDescription
objectObjectthe Javascript object to serialize.
[options.checkKeys]Booleanthe serializer will check if keys are valid.
[options.serializeFunctions]Booleanfalseserialize the javascript functions (default:false).
[options.ignoreUndefined]Booleantrueignore undefined fields (default:true).

Serialize a Javascript object.

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

serializeWithBufferAndIndex(object, buffer)

ParamTypeDefaultDescription
objectObjectthe Javascript object to serialize.
bufferBufferthe Buffer you pre-allocated to store the serialized BSON object.
[options.checkKeys]Booleanthe serializer will check if keys are valid.
[options.serializeFunctions]Booleanfalseserialize the javascript functions (default:false).
[options.ignoreUndefined]Booleantrueignore undefined fields (default:true).
[options.index]Numberthe 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)

ParamTypeDefaultDescription
bufferBufferthe buffer containing the serialized set of BSON documents.
[options.evalFunctions]Objectfalseevaluate functions in the BSON document scoped to the object deserialized.
[options.cacheFunctions]Objectfalsecache evaluated functions for reuse.
[options.cacheFunctionsCrc32]Objectfalseuse a crc32 code for caching, otherwise use the string of the function.
[options.promoteLongs]Objecttruewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits
[options.promoteBuffers]Objectfalsewhen deserializing a Binary will return it as a node.js Buffer instance.
[options.promoteValues]Objectfalsewhen deserializing will promote BSON values to their Node.js closest equivalent types.
[options.fieldsAsRaw]Objectallow to specify if there what fields we wish to return as unserialized raw buffer.
[options.bsonRegExp]Objectfalsereturn BSON regular expressions as BSONRegExp instances.
[options.allowObjectSmallerThanBufferSize]booleanfalseallows the buffer to be larger than the parsed BSON object

Deserialize data as BSON.

Returns: Object - returns the deserialized Javascript Object.

calculateObjectSize(object)

ParamTypeDefaultDescription
objectObjectthe Javascript object to calculate the BSON byte size for.
[options.serializeFunctions]Booleanfalseserialize the javascript functions (default:false).
[options.ignoreUndefined]Booleantrueignore 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])

ParamTypeDefaultDescription
dataBufferthe buffer containing the serialized set of BSON documents.
startIndexNumberthe start index in the data Buffer where the deserialization is to start.
numberOfDocumentsNumbernumber of documents to deserialize.
documentsArrayan array where to store the deserialized documents.
docStartIndexNumberthe index in the documents array from where to start inserting documents.
[options]Objectadditional options used for the deserialization.
[options.evalFunctions]Objectfalseevaluate functions in the BSON document scoped to the object deserialized.
[options.cacheFunctions]Objectfalsecache evaluated functions for reuse.
[options.cacheFunctionsCrc32]Objectfalseuse a crc32 code for caching, otherwise use the string of the function.
[options.promoteLongs]Objecttruewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits
[options.promoteBuffers]Objectfalsewhen deserializing a Binary will return it as a node.js Buffer instance.
[options.promoteValues]Objectfalsewhen deserializing will promote BSON values to their Node.js closest equivalent types.
[options.fieldsAsRaw]Objectallow to specify if there what fields we wish to return as unserialized raw buffer.
[options.bsonRegExp]Objectfalsereturn 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)));

Keywords

FAQs

Last updated on 07 Nov 2018

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc