How do I access and read a local file from html+javascript page running locally

Viewed 78370

I would like to write a small html file that would run locally and manipulate a small text file on my computer. My requirements are:

  • Text file sits in a directory on my computer (test.txt)
  • Html file is in the same directory as the text file (test.html)
  • I would like to use javascript in the html to read and write the text file.

Is this possible at all? If yes, how do I read and write my text file using javascript?

5 Answers

You can also use an hta file extension and it will load in IE where you have access to ActiveX objects. In a pinch you can very quickly get an executable program up and running with minimal effort.

The relevant code is:

<!DOCTYPE html>
<html>
    <head>
        <HTA:APPLICATION
             ID="somethingHere"
             APPLICATIONNAME="YouAppsName"
             WINDOWSTATE="maximize"
        >
         <script language="JScript">
        function ReadFile(filename) {
            try {
                var fso  = new ActiveXObject("Scripting.FileSystemObject");
                var fh = fso.OpenTextFile(filename, 1);
                var contents = fh.ReadAll();
                fh.Close();
                return contents;
            } catch (Exception) {
                return "Cannot open file :(";
            }
        function WriteFile(filename, text) {
            try {
                var fso  = new ActiveXObject("Scripting.FileSystemObject");
                var fh = fso.OpenTextFile(filename, 8, true);
                fh.Write(text);
                fh.Close();
            } catch(Exception) {
                alert("Failed to write.");
            }
        }
            .....
    </script>
    etc.....

Whey not use the fetch() function? Mind you he is going to serve the file using another server

Here is a tutorial of a guy using it https://youtu.be/C3dfjyft_m4

Related