I am trying to read a file type that has a mixture of integers, floats and strings using Javascript.
The file is drag-dropped then, with the File API, read as array buffer and wrapped with a DataView. That takes care of the number types but I had to make my own method for getting text.
DataView.prototype.getAscii = function(byteOffset, byteLength)
{
var bytes = new Array(byteLength);
for (var i = 0; i < byteLength; i++) {
bytes[i] = this.getUint8(byteOffset + i);
}
return String.fromCharCode.apply(null, bytes);
}
It works well enough but I worry about the speed of reading individual bytes for large files. Typed arrays can supposedly be used interchangeably with normal arrays so I tried this:
DataView.prototype.getAscii = function(byteOffset, byteLength)
{
var bytes = new Uint8Array(this.buffer, byteOffset, byteLength);
return String.fromCharCode.apply(null, bytes);
}
I get a “TypeError: Function.prototype.apply: Arguments list has wrong type” message so it doesn’t like my Uint8Array as a parameter.
Is there a better way of reading many characters at once? FileReader#readAsText() reads the whole file but doesn’t give access to any of the binary methods.
You could slice your file with .webkitSlice/.mozSlice and then use readAsText and readAsArrayBuffer for different ranges.