-1

In the below code I take in info from a text file and turn it into an array. Is it standard to then perform all manipulation of the array within this same function or is there some way to bring it out? I plan to rearrange the information in each line of the text file and then download it as a new file. It feels odd to me to put all of this code inside that method, but I don't see a way to bring the array out. Am I correct that I will just have to write the majority of the program inside this function after the reader.readAsText(file) line?

document.getElementById(`file`).onchange = function(event){
    let file = this.files[0];
    let reader = new FileReader();
    reader.onload = function(){
        let fileAsArray = this.result.split(`\n`);
        console.log(fileAsArray);
        for(let i = 0; i < fileAsArray.length; i++){
            console.log(fileAsArray[i]);
        }
    }
    reader.readAsText(file);
};
  • You'll have to do the transformations after the "load" event has fired. There are several options for how to structure the code for doing that, but no matter what it cannot be done until the point in time where you're able to do those `console.log()` calls now. – Pointy Sep 02 '22 at 15:17

1 Answers1

0

The easiest way to do this would be to wrap the callback functionality in a promise and await the result.

function readFile(file){
  return new Promise((resolve,reject)=>{
      let reader = new FileReader();
      reader.onloadend = (event) => resolve(event.target.result);
      reader.readAsText(file);
    });
}


async function printArray(event){
    let fileContents = await readFile(event.target.files[0]);
    let fileAsArray = fileContents.split(`\n`);
    for(let i = 0; i < fileAsArray.length; i++){
        console.log(fileAsArray[i]);
    }
}
<input type="file" onchange="printArray(event)"/>
Bobby Morelli
  • 460
  • 2
  • 7