0

I am trying to read a local .txt file, and assign the content to some variables.

Now I have tried:

  // Empty array to store the string from the text file
  var importedText = [];

  // Fetching .txt file
  fetch('text.txt')
  .then((response) => response.text())
  .then(data => importedText = data.split(/\r?\n/)); // import the string, separated by '\n'

  var t1 = importedText[0]; // these two returns undefined
  var t2 = importedText[1];

It appears that the variable t1 and t2 return undefined, even though both importedText[0] and importedText[1] return the desired string. Also, the array importedText seems to be perfectly fine (array containing the strings read from the text file).

I suspected that the fetch() function does not work that way that we can easily access the importedText inside it.

Can anyone help me with it? Thank you in advance.

Best, GH

0 Answers0