Sometimes, we want to load the contents of a text file into a JavaScript variable.
In this article, we’ll look at how to load the contents of a text file into a JavaScript variable.
How to load the contents of a text file into a JavaScript variable?
To load the contents of a text file into a JavaScript variable, we call text
from the response
object that we get with fetch
.
For instance, we write
const load = async (url) => {
try {
const response = await fetch(url);
const data = await response.text();
console.log(data);
} catch (err) {
console.error(err);
}
};
load("https://example.com");
to create the load
function that calls fetch
to make a GET request to the url
.
Then we call response.text
to get the response body as a text string.
Conclusion
To load the contents of a text file into a JavaScript variable, we call text
from the response
object that we get with fetch
.