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.

Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
valar morghulis
  • 141
  • 1
  • 1
  • 10

1 Answers1

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));
ForrestLyman
  • 1,544
  • 2
  • 17
  • 24
  • 1
    I still cant access this arr outside the fetch. Why? – valar morghulis Jul 26 '18 at 22:08
  • 2
    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. – ForrestLyman Jul 26 '18 at 22:31
  • What I don't understand, why do we need 2x `.then()`, why couldn't we just contain everything in the first? – mmenschig Jul 26 '18 at 23:04
  • response.text() returns another promise. i updated the example with a more concise version. – ForrestLyman Jul 26 '18 at 23:09