Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Binary Files in Client-side JS

I'm wondering if there's any possible way of parsing a binary file in client-side Javascript. I would like to write a page that contains an HTML input form for a binary file ( a sound file is the end game ) and a button that activates a Javascript function that 'parses' the file. Is this possible with client-side Javascript?

I know I can do this with C on the server, but I'd like to avoid anything server-side involved. This is because I'm expecting the task to be computationally intensive and I would like to keep the load and the server low.

From what I've seen on Google, it's possible to parse binary data in Javascript. I'm just not sure how to get the file in the hands of a Javascript function without first passing it to the server.

like image 306
tay10r Avatar asked May 11 '13 08:05

tay10r


People also ask

Does JavaScript support binary data?

You can send JavaScript typed arrays as binary data as well. This is building a 512-byte array of 8-bit integers and sending it; you can use any binary data you'd like, of course.

How does JavaScript handle binary data?

Binary data in JavaScript is implemented in a non-standard way, compared to other languages. But when we sort things out, everything becomes fairly simple. The basic binary object is ArrayBuffer – a reference to a fixed-length contiguous memory area.

Which of the following code lines allows an XMLHttpRequest to return binary data?

Which of the following code lines allows an XMLHttpRequest to return binary data? request. responseType = 'binary'; request.


1 Answers

You can use the FileReader API to read a file client-side

Example:

HTML Markup:

<input id="myfile" type="file"/>

JavaScript:

var fileInput = document.getElementById('myfile');
var fReader = new FileReader();

fReader.onload = function(e) {
  console.log(e.target.result); /// <-- this contains an ArrayBuffer
}

fileInput.onchange = function(e) {
    var file = this.files[0];
    fReader.readAsArrayBuffer(file);
}

JSFiddle: http://jsfiddle.net/wbwHU/ (look at the console for ArrayBuffer output)

like image 75
lostsource Avatar answered Sep 28 '22 09:09

lostsource