Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading bytes from a JavaScript blob received by WebSocket

I have a WebSocket that receives binary messages and I want iterate over the bytes.

I came up with the following conversion function...

// Convert the buffer to a byte array.
function convert(data, cb) {
    // Initialize a new instance of the FileReader class.
    var fileReader = new FileReader();
    // Called when the read operation is successfully completed.
    fileReader.onload = function () {
        // Invoke the callback.
        cb(new Uint8Array(this.result));
    };
    // Starts reading the contents of the specified blob.
    fileReader.readAsArrayBuffer(data);
}

This does work, but the performance is terrible. Is there a better way to allow reading bytes?

like image 511
Deathspike Avatar asked Aug 01 '13 09:08

Deathspike


1 Answers

Have you considered:

socket.binaryType = 'arraybuffer';

The function becomes:

function convert(data) {
     return new Uint8Array(data);
}

Which will not actually have to do any work because it's just a view on the buffer.

like image 76
Esailija Avatar answered Oct 09 '22 09:10

Esailija