Get an array of values using fetch api javascript

Clash Royale CLAN TAG#URR8PPPGet an array of values using fetch api javascript
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.
The console.log(arr) prints an empty array
– nazschi
10 mins ago
have you done a
console.log(arr)?– mmenschig
10 mins ago
console.log(arr)
@mmenschig yes, on the last line of code
– nazschi
9 mins ago
1 Answer
1
You can convert the text response to an array by splitting on newline characters:
fetch('file.txt')
.then(function(response) {
return response.text();
}).then(function(text) {
const arr = text.split(/r|n/);
// do something with your array
});
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
How do you know that nothing is added?
– PM 77-1
10 mins ago