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
msgpack5
msgpack5 is a package that implements the MessagePack serialization format. MessagePack is an efficient binary serialization format that is similar to BSON but is not tied to MongoDB. It aims to be more compact and faster than JSON.
protobufjs
protobufjs is a package that allows you to serialize and deserialize data using Google's Protocol Buffers. Protocol Buffers are similar to BSON in that they provide a way to encode structured data in an efficient binary format, but they require a predefined schema and are more focused on cross-language compatibility.
cbor
cbor is a package that implements the CBOR (Concise Binary Object Representation) data format. Like BSON, CBOR is a binary format that can serialize and deserialize JavaScript objects. However, CBOR is designed to be more compact and to have a wider range of data types than BSON.
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 webpack and the current version is pre-compiled in the browser_build
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.
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="./browser_build/bson.js"></script>
<script>
function start() {
var Long = BSON.Long;
var bson = new BSON();
var doc = { long: Long.fromNumber(100) }
var data = bson.serialize(doc)
var doc_2 = bson.deserialize(data)
}
</script>
A simple example of how to use BSON in Node.js
:
var BSON = require('bson')
var Long = BSON.Long;
var bson = new BSON();
var doc = { long: Long.fromNumber(100) }
var data = bson.serialize(doc)
console.log('data:', data)
var doc_2 = bson.deserialize(data)
console.log('doc_2:', doc_2)
Installation
npm install bson
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.serialize(object, options)
- @param {Object} object the JavaScript object to serialize.
- @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid.
- @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions.
- @param {Boolean} [options.ignoreUndefined=true]
- @return {Buffer} returns a Buffer instance.
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.serializeWithBufferAndIndex(object, buffer, options)
- @param {Object} object the JavaScript object to serialize.
- @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.
- @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid.
- @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions.
- @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields.
- @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into.
- @return {Number} returns the index pointing to the last written byte in the 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.calculateObjectSize(object, options)
- @param {Object} object the JavaScript object to serialize.
- @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions.
- @param {Boolean} [options.ignoreUndefined=true]
- @return {Buffer} returns a Buffer instance.
BSON.deserialize
The BSON deserialize
method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object.
BSON.deserialize(buffer, options)
- @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
- @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
- @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
- @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
- @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance.
- @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
- @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
- @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
- @return {Number} returns the next index in the buffer after deserialization x numbers of documents.
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.
BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)
- @param {Buffer} buffer the buffer containing the serialized set of BSON documents.
- @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.
- @param {Number} numberOfDocuments number of documents to deserialize.
- @param {Array} documents an array where to store the deserialized documents.
- @param {Number} docStartIndex the index in the documents array from where to start inserting documents.
- @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
- @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
- @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
- @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
- @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance.
- @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
- @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
- @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
- @return {Object} returns the deserialized JavaScript Object.
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.