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 file and upload it to your server. A very basic example is uploading  an image or uploading a text file and displaying its content in textarea.

To read any file in javascript, you have to make use of FileReader object. You can read all kind of file types such jpeg, txt, json, png, etc. For images, you can make use of readAsDataURL() function to get base64 encoded string and use it directly as source in image tag. Please check out base64 to image converter online tool to see it in action. For text files, you can make use readAsText() function.

In this tutorial, our goal is to read text file and display its content line by line. We are using FileReader object to read file, detecting line breaks using regex (/\r\n|\n/) and then joining the array using new line character (\n). HTML, CSS and Javascript code is given below.

 

<!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>

 

CSS:

div {
    display: flex;
    flex-direction: column;
    align-items: center;
}

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

 

Javascript:

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); 
    
});

 

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •