Using Javascript to display a string variable in an HTML page is easy:
<html>
<body>
<script>
text = "hello"
document.getElementById("demo").innerHTML = text
</script>
<p id="demo"></p>
</body>
</html>
However I would like to replace "hello" with the contents of a local file, say file.txt. I think this should be easily accomplished using Javascript's fetch() API but I'm running into problems. This,
<html>
<body>
<p id="demo"></p>
<script>
text = fetch('file.txt').then(response => response.text())
document.getElementById("demo").innerHTML = text
</script>
</body>
</html>
will display [object Promise]. I guess I somehow must access the response object but I don't know how that is done.
response.text() returns also a promise. So you have to add another then to get the text.
response.text().then(function (text) {
// do something with the text response
});
text in your code is a promise, not text. You need to use the promise callback:
fetch('file.txt')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text();
})
.then(text => {
document.getElementById("demo").innerHTML = text;
})
.catch(error => {
// Handle/report error
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With