Reading header values from a binary file blob in pure JavaScript

400 Views Asked by At

Suppose I have a bufferArray object buff that holds a file. Suppose, the file has a header with file properties that are different in size and are located at different offsets.

For example:

Offset | Length (bytes) | Property

  • 0, 4, File signature
  • 4, 2, Header size
  • 6, 2, Version of file
  • 8, 8, length property #1 in bytes
  • 16, 8, length property #2 in bytes

etc.

So, I want to read those header entries. ArrayBuffer cannot be accessed or modified directly in JS. We have to use ArrayBufferView.

But the entries are of different size: We have 2, 4, 8 byte (and possibly other sizes) values to read. Subsequently, will I need to use multiple ArrayBufferView's to read a header from 1 file?

const buff = new ArrayBuffer();

var byte2 = new Uint16Array(buffer, byteOffset, length);
var byte4 = new Uint32Array(buffer, byteOffset, length);
var byte8 = ? // JS does not support 64 bit Ints. What should I do?

var signature = byte4[0];
var headerSize = byte2[2];
var fileVersion = byte2[3];

property1 = ? // no 64 bit Int support in JS
property2 = ? // no 64 bit Int support in JS

So, my question is: Is having multiple ArrayBufferView's the way to go, or is there a more elegant approach? Like, setting a JS equivalent of a C struct in one go.

Also, how do I read and store 64 bit (8 byte) Ints from the file header in JS? (Sorry for the second sub-question, but they are really interconnected for this application case. Maybe, post 2 separate answers for extra points.)

0

There are 0 best solutions below