BSON, an acronym for "Binary JSON," provides a binary-encoded serialization of JSON-like documents. Being used as a library, it allows the efficient encoding of data in binary format that is easy to manipulate, making storage and network transfer more efficient. It is a useful tool that adds to the performance of applications that frequently serialize and un-serialize data for storage or transfer.
To utilize BSON, there are different approaches for Node.js and browsers. For a Node.js environment or when using a bundler, following are the steps:
Firstly, you need to install the package:
npm install bson
Once the package is installed, you can proceed with the import and usage as illustrated below:
import { BSON, EJSON, ObjectId } from 'bson';
// const { BSON, EJSON, ObjectId } = require('bson') also works
// create a BSON serialized object
const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
// decode the BSON object back to JSON-like document
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
If working directly in the browser, without a bundler, you can use the .mjs
bundle like so:
<script type="module">
import { BSON, EJSON, ObjectId } from './lib/bson.mjs';
// create a BSON serialized object
const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
// decode the BSON object back to JSON-like document
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
</script>
Note: In both cases, an ObjectId is being serialized and logged, then it's being deserialized and logged again in a JSON-like document format.
BSON official documentation can be found here. It includes detailed guides and specifications on various BSON module components like BSON, EJSON features including methods for BDSOn processing such as .parse, .stringify, .serialize, and .deserialize.