I made a DataView API Wrapper to read binary data from either a string or a binary buffer. You probably want to load it from a file, so you need to make a XHR request. Sadly no ajax wrapper implement it yet.
XHR and Binary
In order to get a binary string one must use the charset=x-user-defined Mime type. If you fail to do so, special characters such as \0
or unicode characters will mess everything up.
Calumny found out that both Firefox and Chrome (nightly builds) implemented a way (sadly not the same) to get the response as an ArrayBuffer.
jQuery Patch
I am a big fan of jQuery to abstract all the browser incompatibilities, therefore I made a small patch in order to support a new data type: binary
.
@@ -5755,6 +5755,7 @@ script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", + binary: "text/plain; charset=x-user-defined", // Vjeux: Add a binary type _default: "*/*" } }, @@ -5934,6 +5935,15 @@ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } + // Vjeux: Set OverrideMime Type + if ( s.dataType == "binary" ) { + if (xhr.hasOwnProperty("responseType")) { + xhr.responseType = "arraybuffer"; + } else { + xhr.overrideMimeType('text/plain; charset=x-user-defined'); + } + } + // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*; q=0.01" : @@ -6228,7 +6238,9 @@ httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, + responseArrayBuffer = xhr.hasOwnProperty('responseType') && xhr.responseType == 'arraybuffer', // Vjeux + mozResponseArrayBuffer = 'mozResponseArrayBuffer' in xhr, + data = mozResponseArrayBuffer ? xhr.mozResponseArrayBuffer : responseArrayBuffer ? xhr.response : xml ? xhr.responseXML : xhr.responseText; // Vjeux- data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" );
Result!
This is now as simple as that to manipulate a binary stream.
$.get( 'data.bin', function (data) { var view = new jDataView(data); console.log(view.getString(4), view.getUint32()); // 'MD20', 732 }, 'binary' ); |
Demo
Now the part you are all waiting for, the demo 🙂 Here's a tar reader in 50 lines of Javascript.