'Read, edit the data and download multiple files in pure JavaScript

Firstly, I allow users to upload multiple files. Then I use loop with fileReader to read all the uploaded files. Next I edit some data of each file and create new files contain each data. Finally, I want to download all of these files using fileSaver library. The problem is that I can only download the last file with the below code. I would be very grateful if someone can fix it. Code:

<html>
<body>
    <!-- Link to FileSaver Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js" integrity="sha512-Qlv6VSKh1gDKGoJbnyA5RMXYcvnpIqhO++MhIM2fStMcGT9i2T//tSwYFlcyoRRDcDZ+TYHpH8azBBCyhpSeqw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <!-- Allow users to upload multiple files -->
    <input type="file" id="real-file" accept=".xml" multiple/>
    
    <script>
        const realFileBtn = document.getElementById("real-file")
        
        realFileBtn.addEventListener("change", function() {
            
            if (realFileBtn.value) {
                
                // Use loop to do for all uploaded files
                for(var i = 0; i < realFileBtn.files.length; i++){
                    
                    var fr = new FileReader()
                    
                    var fileName = realFileBtn.files[i].name
                    
                    fr.readAsText(realFileBtn.files[i]) 
                    
                    fr.onload = function() {
                        
                        // After loading the file, I get the data of it and edit some information (for example: replace "a" with "b")
                        var data = fr.result.replaceAll("a", "b")
                        
                        // I create a new file that contain the edited data with the same name as the uploaded file
                        var myFile = new File(
                            [data],
                            fileName,
                            {type: "text/xml; charset = utf8"})
                        
                        // Then I download that file
                        saveAs(myFile)

                        // The issue is that I can only download 1 file and that file is the last file you uploaded
                        
                        // I want to read the first file, edit its data and download the file contain that data. Then do the same with second file, 
                        // third file,... n file
                    }
                }
            }
        })
    </script>
</body>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source