How to Read Text File in Javascript Line By Line

In this tutorial, you will learn how to read text file in javascript line by line. As a web developer, in some of the applications, it is very common to provide your web users the ability to select a file and upload it to your server.

In case of image upload, we always have to show the image preview before proceeding with the upload process. Similarly, in case of text file upload, we have to show the contents of the text file in a text box.

To read any file in javascript, we can make use of the FileReader object. This object contains the readAsDataURL() method which will help you in generating a base64 encoded string for an image. This base64 encoded string can be used directly as a source in the img tag.

Please check out online base64 to image converter tool to see it in action. To read text files, we can make use of the readAsText() method.

In the following example, we have an input field of type file and a text box. We will select a text file and display its content line by line in the text box. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, input, and textarea). The div element is just a wrapper for the rest of the elements.
  • The input element is of type file which provides us the ability to select a file.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <input type="file">
        <textarea cols="30" rows="20"></textarea>
    </div>
    
    <script src="script.js"></script>
</body>
</html>
div {
    display: flex;
    flex-direction: column;
    align-items: center;
}

textarea {
    margin-top: 15px;
    width: 50%;
}

Javascript

  • We have selected the input element and the textarea using document.querySelector() method and stored them in the input and textarea variables respectively.
  • We have attached a change event listener to the input element.
  • In the event handler function, the files property of the input element returns an array of File objects and we are storing that in the files variable.
  • We are making use of the if statement to verify whether the files array is empty or not. If the user has selected a file, then the length property will always return value greater than 0.  If it is 0, we just want to stop the execution of the function by using the return statement.
  • As you know, arrays have a 0-based index. We are getting the first File object by passing an index of 0 and storing it in the file variable.
  • We are creating an instance of the FileReader object and storing it in the reader variable.
  • We are assigning a custom function to the onload property of the FileReader object. This function will be executed when the load event gets fired.
  • In the load event handler function, we are using the result property to get the contents of the text file.
  • We are using split() function and passing regex pattern /\r\n|\n/ as a parameter. This will generate an array of lines and we are storing that in the lines variable.
  • We are using the join() method to join all lines by a newline character (\n). This will return a string and we are setting that string as the value of the textarea element.
  • We are assigning a custom function to the onerror property of the FileReader object. This function will be executed when an error event gets fired.
  • In the error event handler function, we are calling the alert() method and passing the name property of the error object as a parameter.
  • Finally, we are reading the file by calling the readAsText() method and passing the file variable as a parameter.
let input = document.querySelector('input');
let textarea = document.querySelector('textarea');

input.addEventListener('change', () => {
    let files = input.files;

    if(files.length == 0) return;

    const file = files[0];

    let reader = new FileReader();

    reader.onload = (e) => {
        const file = e.target.result;
        const lines = file.split(/\r\n|\n/);
        textarea.value = lines.join('\n');
    };

    reader.onerror = (e) => alert(e.target.error.name);

    reader.readAsText(file); 
    
});