How to read file using FileReader.readAsText synchronously in JavaScript?

Viewed 575

I am trying to read a CSV file using FileReader.readAsText() in JavaScript. But I am not able to get the value synchronously. I tried multiple approaches. But none is working. Below is the code I have so far:

1st Approach:

<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = {uploadFile} >
    const uploadFile = (event: React.ChangeEvent < HTMLInputElement > ) => {
        let resultSyncOutput = '';

        connst files = event?.target.files;

        if (files && files.length > 0) {
            readAsTextCust(files[0]).then(resultStr => {
                resultSyncOutput = resultStr;
            });
        }
      
      // At this line I am not able to get the value of resultSyncOutput with the content of file sychronously
      
      //Do something with the result of reading file.
      someMethod(resultSyncOutput);
    }

async function readAsTextCust(file) {
    let resultStr = await new Promise((resolve) => {
        let fileReader = new FileReader();
        fileReader.onload = (e) => resolve(fileReader.result);
        fileReader.readAsText(file);
    });

    console.log(resultStr);

    return resultStr;
}

This is the first approach I tried ie, using async/await. I also tried to do it without aysnc/await and still was not able to succeed. It is critical for this operation to be synchronous. Also use of Ajax is not allowed in project.

NB: I checked a lot of answers in Stack Overflow and none provides a solution to this problem. So please do not mark this as duplicate. Answer to this particular question is not provided anywhere.

Please help me even if this looks simple to you

2 Answers

You need to set a callback function for the onload event callback to get the results. Also notice that you need to call readAsText on the uploaded CSV file.

You can use FileReader API inside input's onChange callback this way:

<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = function (event: React.ChangeEvent<HTMLInputElement>) {
    const reader = new FileReader();

    reader.onload = (e) => {
        console.log(e.target?.result) // this is the result string.
    };

    reader.readAsText(event.target.files?.[0] as File);
  };

No need for async/await as well.

I found the solution resultSyncOutput = await readAsTextCust(files[0]); and declaring the calling function as async worked.

Related