0

I want to read a file that's saved in the same folder. Then I want to show its content in a div in index.html. The problem: when I used require("fs") it didn't work since it wasn't running server-side. I have been looking around and can't find a simple answer. I want to make my website a little dynamic, so here is the code that should fire upon a button click:

function videos() {
    var body = *read a file("insertfilename")*;
    console.log(body);
    document.getElementById("body").innerHTML = body;
}

"body" in this case is just the id I gave the div.

!EDIT!

Now to explain it further. I want to use it as my main website. When I go onto there it should open an empty html file, which has a scriptfile as source. "onload" it should read a file , which is also already on the server, and put its content into a div inside of the body. If I click on a hotlink or a Button, it should read another file and put that content into that div instead. Maybe that gives a little clarification on what I am trying to do. I dont want to reload to open other sites of mine.

2 Answers2

0

Seems like you need some basic file fetching since you are not using a server. Have you tried FileReader for javascript? It is a very simple and straightforward object. The example on the page seems similar to what you are trying to accomplish, except you want to fetch the file, not the user.

Scott May
  • 1
  • 1
0

You can use AJAX. It stands for Asynchronous JavaScript And XML. You can send asynchronous requests to server with it. Just make sure that file that you are requesting is on the same domain as JS file.

function videos() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() { //this will execute when you receive response from the server
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("body").innerHTML = this.responseText;
            console.log(this.responseText)
        }
    };
    xhttp.open("GET", "filename.txt", true);
    xhttp.send();
}

Here is W3schools tutorial if you want to learn more.

  • The problem with that version is, that I would have to set up a server, but I dont wanna do that. I have one to which I will upload it after I am finished, but the main problem here is, that I do not know if it'l be able to retrieve the text from a file and convert it into an html body. I just really dont want to have to use a port for that and just stay on my main website as intended – Erik Klatscho Apr 03 '18 at 17:44
  • It should be. If the text file is in the same folder as JS you can use relative path to it, no need to use IP or port – Petr Šícho Apr 03 '18 at 18:46
  • You can try it from localhost, if it won't work change the path to: file://C:/path/to/file.txt . See:https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file – Petr Šícho Apr 03 '18 at 21:48