In this article, we will learn how to read text files line-by-line using JavaScript.
We can read and view the content of the text file using FileReader()
object in our browser or terminal using JavaScript.
What is FileReader() ?
The FileReader()
is an object provided by JavaScript that let a web-application read content of files stored on a user’s computer. It uses File or Blob object to specify or read the content of the file.
FileReader can read text files that the user specifically selected.
Let us see with an example.
Read Local Text File Using JavaScript
Here, we will upload a simple text file (.txt) using an HTML input field and display the content of it on our terminal / console.
HTML Code:
<body>
<h1>
Read Local text file using JavaScript
</h1>
<input type="file" name="myfile" id="myfile" />
<p>check console for result</p>
<script src="main.js"></script>
</body>
JavaScript code:
let file = document.getElementById("myfile");
file.addEventListener("change", function () {
var reader = new FileReader();
reader.onload = function (progressEvent) {
console.log(this.result);
};
reader.readAsText(this.files[0]);
});
Code Explanation
Here, we have an input field that helps us to select a text file from our computer.
In the Script file, we have selected the file using getElementById()
.
We have added an event listener to the file, which listens to an change
event. It gets triggered when a file is selected in the input field.
Once the change event is triggered the function will read the file using FileReader()
and then console.log the content inside it to the terminal of your browser.
reader.onload
: It runs once the reading operation is completed.
readAsText()
: This method reads the file content of the selected Blob or File
this.result
: It returns the file content on the terminal.
Related Topics: