1

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.

sammosummo
  • 385
  • 1
  • 2
  • 15
  • You need to wait till `fetch` completes. Try using `await` like this: `text = await fetch('file.txt').then(response => response.text()) document.getElementById("demo").innerHTML = text` – Ninad Aug 08 '19 at 11:23
  • @Nimad this doesn't seem to work. – sammosummo Aug 08 '19 at 11:46

3 Answers3

0

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
});
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
0

The problem is you're doing document.getElementById("demo").innerHTML = text before the prmise has resolved and you have your text. Try doing

text = fetch('file.txt').then(response => {
   document.getElementById("demo").innerHTML = response.text()
})
Geraint
  • 2,974
  • 2
  • 21
  • 38
0

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 
});
Simtschy
  • 1
  • 1