RJK RJK - 2 months ago 22
Javascript Question

How to save text file contents to Javascript variable?

I'm trying to read a text file of over 150,000 lines of text. I want to be able to read the text file and pass it as a parameter for processFileContent.

I tried it this way, but it doesn't work. Also, is there a better way to do this for such big data?

function readFile(file) {
var reader = new FileReader();
reader.onload = function (evt) {
var data = evt.target.result;
};
reader.readAsText(file);
return data;
}

document.getElementById('file').addEventListener('change', readFile, false);

var data = readFile();

function processFileContent(data) {
var list = data.split('\n');
...

Answer

FileReader.onload event returns results asynchronously. You can use a callback or Promise to return result of FileReader to processFileContent. Also file at readFile would be event object, not .files property of event.target.

function readFile(event) {
  var file = event.target.files[0];
  if (file) {
    new Promise(function(resolve, reject) {
      var reader = new FileReader();
      reader.onload = function (evt) {
        resolve(evt.target.result);
      };
      reader.readAsText(file);
      reader.onerror = reject;
    })
    .then(processFileContent)
    .catch(function(err) {
      console.log(err)
    });
  }
}

document.getElementById('file')
.addEventListener('change', readFile, false);

function processFileContent(data) {
  var list = data.split('\n');
  ...