Monday, December 3, 2012

Javascript class to read a binary file in a browser

I found this nice open source code at https://github.com/vjeux/jDataView that provides a class for reading binary files in the browser.

The following Javascript code snippet is a simple example I wrote showing how to parse through a binary file using the HTML5 FileReader and the jDataView class.

function onFileButtonChange(evt){
    var files = evt.target.files;
    var f = files[0];

    //create a new instance of the HTML5 FileReader
    var reader = new FileReader();    
    //onload is called when the binary file is loaded
    reader.onload = function(e){        
        //store the binary array buffer in the buff variable
        var buff = e.target.result;
        
        //create a new instance of the jDataView
        var dv = new jDataView(buff);
        
        var offset = 0;
        //read a little endian signed integer (4 bytes) from byte offset 0. 
        var field1 = dv.getInt32(offset,true);
        
        offset+= 4;    //Move to the next field
        //read a little endian double (8 bytes) from byte offset 4
        var field2 = dv.getFloat64(offset,true);
        //...etc...
    };
    //read in a binary file as an ArrayBuffer
    reader.readAsArrayBuffer(f);
}

Visit the project repository for more details about the jDataView class.

Note that the HTML5 FileReader object's readAsArrayBuffer method has only been implemented in Chrome and FireFox 7+ at this point in time.

2 comments:

  1. Do you know How to read album picture
    from a mp3 file using jdataview and jbinary reader

    ReplyDelete