florianschmidt1994
florianschmidt1994

Reputation: 23

How to convert binary data from binaryjs to string / text

My BinaryJS webclient receives binary data, how do i convert it back to the text input which the server sent?

The Server (with NodeJS), which creates a Websocket, uses BinaryJS because it gets the data to transmit as a stream, and i wanted to forward that data to the client using Websocket streaming.

The web client looks the following:

  <html>
  <head>
    <script src="http://cdn.binaryjs.com/0/binary.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
    <script src="text-encoding/lib/encoding.js"></script>
    <script src="decode.js"></script>
    <script>
      // Connect to Binary.js server
      var client = new BinaryClient('ws://localhost:9000');
      // Received new stream from server!
      client.on('stream', function(stream, meta){
        // Buffer for parts
        // Got new data
        stream.on('data', function(data){
          $( ".inner" ).append(data+"<br />");
        });
        stream.on('end', function(){
        });
      });
    </script>
  </head>
  <body>
    <div class="inner">Output:</div>
  </body>
  </html>

Sadly my output is not the input text but only something like this:

[object ArrayBuffer]

Edit: Found a possible solution:

As the data is UTF-8 encoded, i could simply decode it using a function someone posted in another question:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

Upvotes: 1

Views: 1488

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

There are two cases here:

I assume you are referring to this question: Uint8Array to string in Javascript

Note that the fromCharCode answer there explicitly says that it does not decode UTF8 properly. Your best bet would be to decode the ArrayBuffer using a FileReader. You are also incorrectly processing this content in the data handler, not you should be aggregating it first.

client.on('stream', function(stream, meta){
    var parts = [];
    stream.on('data', function(data){
        parts.push(data);
    });
    stream.on('end', function(){
        var blob = new Blob(parts);
        var reader = new FileReader();
        reader.onload = function(){
            $( ".inner" ).append(reader.result + "<br />");
        };
        reader.readAsText(blob);
    });
});

Now that said, my actual suggestion is that you not use Binary.js for this case. The whole point of it is to transfer binary data. If you are planning to transfer mostly text, you should look into using more text-oriented libraries like Socket.IO.

Upvotes: 1

Related Questions