Read txt file in HTML, CSS, JS and read it line by line

How do I read a txt file in frontend js?

You need to use a request to get the contents of the file, them you can read it’s text content. I would recommend using fetch, but you could also use an XMLHttpRequest.

Something like this should work;

fetch("path/to/file.txt")
    .then(function (res) {
        return res.text();
    })
    .then(function (data) {
        console.log(data);
    });

To be clear, this will get you the entire contents of the text file. I don’t believe there’s a way to read a text file line by line with front-end JavaScript, but you can get the individual lines by splitting the file’s contents by new line characters (data.split("\n");).

Didn’t see your edit hehe

1 Like

Yep, the line breaks will all be \n so you can just split the file contents by that character to get each individual line.

1 Like

What does res and data mean btw? What is their difference?

I’m assuming data means, well, data. And res means the result of the fetch function.

The code simply gets the result, and changes it into text form. Then, it gets passed through into the next .then function, where it becomes data. After, it gets logged to the console.

1 Like

Is the response object, like http code, headers, etc.

Is the actual text of the file.

1 Like

res is not useful to us. It’s the result of the fetch function as others have said. res has a number of useful methods that return promises, however, that can be used to get the data we want. In this case we use text, but another commonly used one is json, which we would use if we were getting JSON data from a JSON file or API. data value the text promise returns (eventually).

2 Likes

Thanks for the answer. But I have another question: how do I print it line by line?

In python you do

for line in data.split("\n"):
  print(line)

But doing that on JS returns numbers

in references the properties of an object, in an array that’s the indexes of each element. You can use of to iterate through each element:

for (const item of array) {
    console.log(item);
}

But generally it’s always preferential to use the generic for loop:

for (let i = 0; i < array.length; i++) {
    console.log(array[item]);
}
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.