Riley Griffis
Riley Griffis

Reputation: 31

Splitting a .txt file into a JavaScript Array using FileReader.readAsText()

I've used FileReader.readAsText() to import a file and import it into my array, but it creates a new array that ends up pushing into the first position of my existing array. When I try to index that array it apparently is "undefined" even though I can clearly see the value in my console.log command. My test .txt file reads

aaa
bbb
ccc
ddd
eee
ddd
eee
eee

I want to read the file and store it into an array by splitting each line '''

        var guestList = []
        document.getElementById('inputfile') 
        .addEventListener('change', function loadFile() { 
          
        var fr=new FileReader(); 
        fr.onload=function(){ 
          guestList.push(fr.result.split('\n')); 
          
        } 
        console.log(guestList)
          
        fr.readAsText(this.files[0]);
    }) 
    console.log(guestList)

''' Here is what my console looks like: [] 0: (9) ["aaa", "bbb", "ccc", "ddd", "eee", "ddd", "eee", "eee", ""] length: 1 proto: Array(0)

Upvotes: 2

Views: 1250

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

You're only pushing a single item to the guestList - the result of splitting the file. Instead, just use the result of the .split, instead of surrounding it in another array - and make sure to log the results inside the callback, not outside.

Also, for multi-system compatibility, some environments use line feed characters as well as newlines. Consider using a regular expression instead, to optionally match a linefeed followed by a newline:

document.getElementById('inputfile').addEventListener('change', () => {
  const fr = new FileReader();
  fr.onload = () => {
    const guestList = fr.result.split(/\r?\n/);
    console.log(guestList);
  };
  fr.readAsText(this.files[0]);
});

Upvotes: 1

Related Questions