[Solved] Using FileReader API in Javascript

[Solved] Using FileReader API in Javascript
0.0 0

#1

My goal is to tread a text file with a list of numbers spearated by a newline/carriage return, and then get it into an array of the numbers.

I can read it using some sample code that uses readAsBinaryString is depreciated, so I’m trying to use the readAsArrayBuffer, which is the suggested replacement.

I’m reading the API docs, but can’t really make sense of it:
https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer

this documentation is also really slim:

I’m following some code examples but would also like to understand the docs which I am struggling with.

using an Array Buffer seems like a catch 22.
The array buffer requires a size specified before it is created, but I don’t know the size of the uploaded file until after it is read.

maybe I just need a readAsText method ?

Sample file I’m uploading is a text file that looks like this…only with 100,000 rows

54044
14108
79294
29649
25260
60660
2995
53777
49689
9083
16122
90436
4615
40660
25675
58943
92904
9900
95588

#2

Something like this worked, sharing in case anyone comes across and needs the info as well:

  reader.onloadend = function(evt) {
    if (evt.target.readyState == FileReader.DONE) { // DONE == 2
      document.getElementById('byte_content').textContent = evt.target.result;
      document.getElementById('byte_range').textContent =
        ['Read bytes: ', start + 1, ' - ', stop + 1,
          ' of ', file.size, ' byte file'].join('');

      var textArr = evt.target.result.split(/\r\n|\r|\n/g);
      var sortArr = textArr.map(function(num) {
        return parseInt(num)
      })

      console.log(sortArr.slice(0,9))


    }
  };

  var blob = file.slice(start, stop + 1);
  reader.readAsText(blob);