How to read text file in JavaScript (line by line)
This article is about how to read text file in JavaScript line-by-line from local computer using Html input field.
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:
Related Posts
JavaScript - Show and hide div on button click using JavaScript
This post is about how to show and hide a div on button click using JavaScript. We will change the CSS property of the element using JavaScript to hide and show the content.
Get user location from browser using JavaScript
Tutorial on how to get user location like latitude and longitude from our browser using geolocation() function in JavaScript.
How to Get the ID of a Clicked Button or Element in JavaScript
Find out how to get the id of a button when clicked in JavaScript using onclick event listener and passing on the this.id or this.target.id.
JavaScript - How to export multiple functions from a file
In this article, we will be covering how we can export and import multiple functions in JavaScript.
