javascript automatically read the file in the same directory, and put it on the content

Viewed 46

is it possible on HTML page load, automatically (without the user input)read the file in the same directory, and put it on the content?

consider text file (a.txt) in the same folder as my HTML file (index.html)

for example

var reader = new FileReader();
    reader.onload = function (e) {
    const fileText = await fetch("a.txt").text();
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText; 
    }

add HTML code

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Page</title>
<meta name="generator" >
<style type="text/css">
</style>
<script type="text/javascript"  defer>     
 
 async function getTextFile1() {
  try {
    const response = await fetch("/a.txt");
    const fileText = await response.text();
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText; 
  } catch (error) {
    console.log(error);
  }
 }
 
   async function getTextFile() {
    const fileText = await fetch("a.txt").text();
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText;
}

window.onload = getTextFile1;
</script> 
</head>
<body>
<div  >hsfghfghdfghdfg
   </div>
   <div id="about_layer">
   </div>
</body>
</html>

1 Answers

Fetch returns a Promise that resolves to a Response object. If you want to decode the response as text, then you'll have to await the text() method as it also returns a Promise, which resolves to a string.

As for on page load, just make sure you add a defer tag to your script to ensure that your script is called after the DOM is loaded.

(async function() {
  try {
    const response = await fetch("./a.txt", {
      mode: 'no-cors'
    });
    const fileText = await response.text();
    const tagElement = document.getElementById("about_layer");
    tagElement.innerText = fileText; 
  } catch (error) {
    console.log(error);
  }
}())
<script src="yourscript.js" defer></script>
Related