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

featured Image

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.

read text file using Javascript

Edit 4o9ps

Related Topics:

Copy Text From An HTML Element To Clipboard-JavaScript

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *