How to read a local text file using JavaScript?

HTML 5 furnishes a standard method for interfacing with neighborhood documents with the assistance of File API. The File API permits collaboration with single, numerous just as BLOB documents. The FileReader API can be utilized to peruse a document nonconcurrently as a team with JavaScript occasion taking care of. Be that as it may, every one of the programs don’t have HTML 5 help so it is vital to test the program similarity prior to utilizing the File API. There are four inbuilt techniques in the FileReader API to peruse nearby documents:

How to read a local text file using JavaScript?

  • FileReader.readAsArrayBuffer(): Reads the substance of the predefined input document. The outcome trait contains an ArrayBuffer addressing the record’s information.
  • FileReader.readAsBinaryString(): Reads the substance of the predetermined information document. The outcome characteristic contains the crude paired information from the document as a string.
  • FileReader.readAsDataURL(): Reads the substance of the predefined input document. The outcome trait contains a URL addressing the record’s information.
  • FileReader.readAsText(): Reads the substance of the predetermined information document. The outcome quality contains the substance of the document as a text string. This technique can accept encoding form as the second argument(if required). The default encoding is UTF-8.

For this situation we are utilizing FileReader.readAsText() technique to understand nearby .txt document.

<!DOCTYPE html>
<html>
 
<head>
    <title>Read Text File</title>
</head>
 
<body>
    <input type="file" name="inputfile"
            id="inputfile">
    <br>
  
    <pre id="output"></pre>
     
    <script type="text/javascript">
        document.getElementById('inputfile')
            .addEventListener('change', function() {
             
            var fr=new FileReader();
            fr.onload=function(){
                document.getElementById('output')
                        .textContent=fr.result;
            }
             
            fr.readAsText(this.files[0]);
        })
    </script>
</body>
 
</html>

JavaScript

This code prints the substance of the info document precisely equivalent to is there in the information record.

JavaScript is most popular for page improvement yet it is additionally utilized in an assortment of non-program conditions. You can gain JavaScript starting from the earliest stage by following this JavaScript Tutorial and JavaScript Examples.

Also Read: How to Install Minecraft on Linux?

Leave a Reply

Your email address will not be published.