1

I am currently working with the fetch API in JavaScript. I have a text file I'd like to read from called sample.txt. I would like to grab the different lines out of the text file and save it in an array so I can work with it. I've been searching for how to save it as an object, but I think I've been using the code for JSON and not for text. Please give any suggestions?

sample.txt

apple
banana
orange
grape

index.js

let fruitArray; //initialized new array

fetch('sample.txt') // fetch text file
.then((resp) => resp.text())
.then(data.split(/\r?\n/) = fruitArray)) //tried to assign each separate line as an element of fruitArray

Expected Output

fruitArray = ['apple', 'banana', 'orange', 'grape'];

1 Answer 1

4

let fruitArray; doesn't create a new array - you have to actually declare an array like [] for that. But it would be better to declare the array only once the response comes back, and then pass it around if needed.

.then accepts a function as a parameter, not a plain code block. The first parameter of the .then callback is the result of the resolution of the previous promise - which here is the full string.

When assigning (=), the left hand side needs to be a variable (or a property).

fetch('sample.txt') // fetch text file
  .then((resp) => resp.text())
  .then(data => {
    const fruitsArray = data.split(/\r?\n/);
  }) 
Sign up to request clarification or add additional context in comments.

2 Comments

thank you! That did the trick. Do you know of any way to access the new fruitsArray outside of the fetch call?
You should call whatever function needs it with the parsed fruitsArray.

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.