Apu
January 19, 2024 .
#HowTo
.
#Javascript
❌
How do I load the contents of a text file into a javascript variable?
I have a question about loading the contents of a text file into a JavaScript variable. I want to load the contents of the file /robots.txt into a variable.
<script>
var fileContents;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
fileContents = this.responseText;
console.log(fileContents)
}
};
xhttp.open("GET", "/robots.txt", true);
xhttp.send();
</script>
This code seems to work, but I'm not entirely sure about its efficiency and if there's a better way to achieve this. Can someone provide an alternative solution or suggest improvements?
save
listen
AI Answer
How do I load the contents of a text file into a javascript variable?
4
I have a question about loading the contents of a text file into a JavaScript variable. I…
asked
Apu
4 answers
2915
I have a question about loading the contents of a text file into a JavaScript variable. I…
Answer Link
answered
Apu
fetch("/robots.txt")
.then(response => response.text())
.then(data =>{
var fileContents = data;
console.log(fileContents);
});
The Fetch API provides a cleaner and more Promise-based approach to make HTTP requests. It simplifies handling responses and is widely supported in modern browsers.
if (fileContent.includes("User-agent")) {
console.log("User-agent found!");
}else{
console.log("User-agent not found.");
}
This code snippet uses the includes method to check if "User-agent" exists in the fileContent variable. You can replace the console.log statements with your desired actions.