Skip to content
Advertisement

Sending Uint8Array (BSON) in a JSON object

I’m using the ‘bson‘ npm package in the browser for converting / serializing a JSON object to BSON. The documentation says that it returns a Node.js buffer. The documentation of Node.js says that a buffer is of type ‘Uint8Array’. Now I want to send this Uint8Array in another JSON object (infoJSON) but JSON does not support Uint8Array. I tried to convert the buffer (Uint8Array) to a simple array, inserting it in the JSON object (infoJSON) and then I convert it back to Uint8Array directly out of the JSON object. But this new Uint8Array can not be deserialized back to the original person object (see the result). It is broken.

Why I’m using BSON? I want to split the original object into multiple chunks to send it through a WebRTC data channel which has a limitation of data size. I need to be able to identify each chunk (type). It is the reason why I am using nested objects.

JavaScript

Result:

result

Advertisement

Answer

This is because Bson.serialize and Bson.deserialize use a Node.js like Buffer object.

You can correct this by using the underlying ArrayBuffer to create a Uint8Array (test online) and use then use Buffer.from :

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement