2

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)

1 Answer 1

1

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]);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.