2

On my server file system I have a directory which contains some .bin file filled with 16 bit integers.

How can I load a Uint16Array variable with the content of a specific .bin file in Node.js?

I already tried:

var arrayFromBinFile = new Uint16Array('./myDirectoryContainingBinFiles/selectedFile.bin')

By using console.log in node.js all I get is:

{ 
  BYTES_PER_ELEMENT: 2,
  get: [Function: get],
  set: [Function: set],
  slice: [Function: slice],
  subarray: [Function: subarray],
  buffer: { slice: [Function: slice], byteLength: 0 },
  length: 0,
  byteOffset: 0,
  byteLength: 0 
}
mrcointreau
  • 322
  • 5
  • 15
  • 1
    Why would you expect that [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) takes a file path as argument? You need to read the file content first. Have a look at [`fs.readFile`](http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback). – Paolo Moretti Feb 27 '15 at 15:55
  • Thank you @PaoloMoretti for driving me to the problem solution. Besides encapsulating the typed array creation into the `fs.readFile` function I also had to convert the Node.js `Buffer` to a JavaScript `ArrayBuffer`. – mrcointreau Mar 02 '15 at 11:30
  • I'm glad you solved the problem by yourself. I wanted to post a solution using `ArrayBuffer`, but without file samples I wasn't sure if it was correct. Thanks for sharing the answer! – Paolo Moretti Mar 02 '15 at 11:49

1 Answers1

3

I came up with the following solution

fs.readFile('./myDirectoryContainingBinFiles/selectedFile.bin', function(err, data)
{
    if (err) throw err;
    terrainData = new Uint16Array(toArrayBuffer(data));
});

Where the toArrayBuffer function, reported in the accepted answer of from Convert a binary NodeJS Buffer to JavaScript ArrayBuffer, is defined as

function toArrayBuffer(buffer) {
    var ab = new ArrayBuffer(buffer.length);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; ++i) {
        view[i] = buffer[i];
    }
    return ab;
}
Community
  • 1
  • 1
mrcointreau
  • 322
  • 5
  • 15