Search code examples
javascriptreactjsfile-uploadsynchronous

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


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


Solution

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