Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read a File in Javascript

How to read a local text file using JavaScript?

HTML 5 provides a standard way to interact with local files with the assistance of File API. The File API allows interaction with single, multiple as well equally Hulk files. The FileReader API can be used to read a file asynchronously in collaboration with JavaScript consequence handling. However, all the browsers do not have HTML 5 support so it is important to examination the browser compatibility before using the File API. At that place are iv inbuilt methods in the FileReader API to read local files:

  • FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file's information.
  • FileReader.readAsBinaryString(): Reads the contents of the specified input file. The issue attribute contains the raw binary data from the file as a cord.
  • FileReader.readAsDataURL(): Reads the contents of the specified input file. The result attribute contains a URL representing the file'south information.
  • FileReader.readAsText(): Reads the contents of the specified input file. The result aspect contains the contents of the file every bit a text string. This method can take encoding version as the second statement(if required). The default encoding is UTF-8.

In this case we are using FileReader.readAsText() method to read local .txt file.

<!DOCTYPE html>

<html>

<caput>

<title>Read Text File</title>

</caput>

<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= part (){

document.getElementById( 'output' )

.textContent=fr.result;

}

fr.readAsText( this .files[0]);

})

</script>

</body>

</html>

This code prints the content of the input file exactly the same as is there in the input file.

JavaScript is best known for web folio development merely information technology is too used in a diversity of not-browser environments. Yous tin can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


bardonschistermin1948.blogspot.com

Source: https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/