Search code examples
javascriptpythonblobtornadobson

BSON decode from Blob


I use Tornado to work with the client application using Javascript. For data exchange uses BSON. Because Tornado to send data uses JSON, I wrote my function send via Websocket:

def write_bson(self, message):
    message = BSON.encode(message)
    self.ws_connection.write_message(message, binary=True)

Because "binary=True" in the browser I get a Blob and not understand how to perform BSON decode the received message.

I tried the following way to perform decode, in the comments I specified the output console.log:

    t = new WebSocket(url);
    t.onmessage = function(event) {
        console.log(event.data); // Blob { size: 390, type: "" }

        console.log(BSON.deserialize(event.data)); // Error: corrupt bson message

        var reader = new FileReader();
        reader.onload = function(e) {
             console.log(e.target.result); // ArrayBuffer { byteLength: 390 }
        };
        var data = reader.readAsArrayBuffer(event.data);

        console.log(BSON.deserialize(data)); // Error: corrupt bson message

How do I decode BSON?


Solution

  •     var reader    = new FileReader();
        reader.onload  = function() {
            uint8Array  = new Uint8Array(this.result);
            console.log(BSON.deserialize(uint8Array));
        }
        reader.readAsArrayBuffer(event.data);