JavaScript Answers

How to use JavaScript to read a local text file and read line by line?

Spread the love

To read a local text file line by line using JavaScript, you can use the File API provided by modern browsers. Here’s a step-by-step guide on how to achieve this:

1. Create an HTML file input element

You’ll need an <input type="file"> element in your HTML to allow users to select the text file they want to read.

<input type="file" id="fileInput" />

2. JavaScript code to read the file

You’ll need JavaScript code to handle the file input change event and read the selected file line by line. Here’s how you can do it:

  .addEventListener("change", function (event) {
    var file =[0];
    var reader = new FileReader();

    reader.onload = function (event) {
      var contents =;
      var lines = contents.split("\n");

      lines.forEach(function (line) {
        // Do something with each line


This JavaScript code listens for changes in the file input element.

When a file is selected, it reads the contents of the file using FileReader.

Once the file is loaded, it splits the contents by newline (\n) characters to get an array of lines.

Then, it iterates over each line and does something with it.

3. Access-Control-Allow-Origin header

If you’re trying to read a file from the local file system (e.g., using file:// protocol), you may run into CORS (Cross-Origin Resource Sharing) issues in some browsers.

In this case, you might need to run a local server to serve the HTML file, or you can use browser extensions or flags to disable CORS temporarily for testing purposes.

4. Browser Support

Keep in mind that the File API is supported in modern browsers, but it might not work in older browsers.

Always check compatibility if you need to support a wide range of browsers.

Make sure to place the JavaScript code within <script> tags in your HTML file or in an external JavaScript file linked to your HTML.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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