How to read text file in JavaScript (line by line)


In this article we will learn how to read text file 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 which let a web-application to read content of files stored in user's computer. It uses File or Blob object to specify or read the content of the file.

FileReader can read text files which 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 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 a input field which help us to select a text file from our computer.

In the Script file, we have select the file using getElementById().

We have added an event listener to file, which listen to a change event. It get 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 selected Blob or File

this.result : It returns the file content on the terminal.

Related Topics:

Copy Text From An HTML Element To Clipboard-JavaScript


💾 Recommended Articles