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 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.
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() {
const Long = BSON.Long;
const doc = { long: Long.fromNumber(100) }
const data = BSON.serialize(doc)
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) };
const data = BSON.serialize(doc);
console.log('data:', data);
const doc_2 = BSON.deserialize(data);
console.log('doc_2:', doc_2);
Installation
npm install bson
Documentation
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.
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() };
console.log(BSON.deserialize(BSON.serialize(obj)));