1

I am using fetch api to read a txt file via javascript. I want to load the contents of the txt file which are separated by new line in an array.

Text file:

A
B
C

I need it in the following format:

arr = ["A", "B", "C"]

Below is the code I tried

var arr = []
fetch('file.txt')
  .then(function(response) {
    return response.text();
  }).then(function(text) {
arr.push(text)
console.log(text)

    });
  console.log(arr)

Nothing gets added to my array, however the data from the text file gets printed on the console.

5
  • How do you know that nothing is added? Commented Jul 26, 2018 at 21:55
  • The console.log(arr) prints an empty array Commented Jul 26, 2018 at 21:55
  • have you done a console.log(arr)? Commented Jul 26, 2018 at 21:55
  • @mmenschig yes, on the last line of code Commented Jul 26, 2018 at 21:56
  • Move log(arr) right after log(text) to see the result. Commented Jul 26, 2018 at 22:06

1 Answer 1

6

You can convert the text response to an array by splitting on newline characters:

function fetchData() {
    return fetch('data.txt')
            .then(response =>
                response.text().then(text => text.split(/\r|\n/)));
}

fetchData().then(arr => console.log(arr));

Sign up to request clarification or add additional context in comments.

4 Comments

I still cant access this arr outside the fetch. Why?
Thats because fetch is going to return a promise, and JavaScript does not wait for it to complete before moving on. This would be a good spot to use async/await if you want this code to function synchronously. I'll update the answer to give a full example.
What I don't understand, why do we need 2x .then(), why couldn't we just contain everything in the first?
response.text() returns another promise. i updated the example with a more concise version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.