How to read a text file from URL in JavaScript using async await

← PrevNext →

I have shared an article here before showing how to save form data in a text file using JavaScript. Now, here I’ll show you how to read a text (.txt) file from URL line by line in JavaScript.

The text file URL

Here’s the URL of the text file (a .txt file). I have stored form data in this file. Now I’ll extract or read the data as it is from the file and show it on a web page.

The Script
  <!--show data here-->
  <div id='textData'></div>
  const readTxt = async() => {
    let url = "../../library/formData.txt";
    let response = await fetch (url);
    const txt = await response.text().then(( str ) => {
        return str.split('\r');    // return the string after splitting it.
    let result = txt;
    let ele = document.getElementById('textData');
    for (i = 1; i <= result.length - 1; i++) {
      ele.innerHTML = ele.innerHTML + '<br />' + result[i];

  readTxt ();
Try it

In the above code, I am using async and await functions to extract data from a text file using a URL.

You can show the data as it is (in a straight line), without running the for loop. However, I wanted to the show the data in a more readable format.

Happy coding. 🙂

← PreviousNext →