15

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?

1
  • Initially it looked like this was a duplicate and I voted to close. Sorry for that. My vote is locked in, and I can't undo the closing vote. If you're on a windows system, I have a few suggestions for you.
    – KooiInc
    Commented Jun 18, 2011 at 16:19

5 Answers 5

14

As is being discussed in Itay Moav's answer, writing to a local file with a local HTML file is perhaps going to be an issue without running in an elevated privilege mode and having additional Javascript capabilities (that allow you to save local files).

However, accessing a local file from an HTML file is entirely possible. Below is some example code.

mytext.txt

My local text file

local.html

<html>
<head>
<base href="file:///C:/path/to/your/folder/"/>
<script>
window.onload = function(){
    var iframe = document.createElement('iframe');
    iframe.id = 'iframe';
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    iframe.src = 'mytext.txt';
    setTimeout(function(){
        var text = document.getElementById('iframe').contentDocument.body.firstChild.innerHTML;
        alert(text);
    }, 1000);
}
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

This will make an alert 1 second after the html page loads (to allow the iframe to load first), and will contain the content within the mytext.txt file.

Note, if it's plaintext, Firefox will wrap it with a PRE element, which is why I did firstChild. Also, note the use of the BASE element, which points to your local directory with your files.

3
  • thanks for the suggestion. is it possible to write the file somehow, if needed?
    – gyurisc
    Commented Jun 20, 2011 at 4:11
  • @gyurisc - Not unless you have a locally-run script (such as a JScript) with special capabilities. For instance, Javascript does not allow for directory discovery and file manipulation; you would need Javascript with local directory capabilities. Commented Jun 20, 2011 at 4:14
  • 1
    Firefox says permission denied.
    – Andrew
    Commented Dec 4, 2017 at 18:17
11

The example given by Jared works fine. However setting an unknown watiting time is not atractive. Instead attach an onload event to the iframe calling a function reading the contents of the text-file an doing whatever as soon as possible.

Here is a revised example:

<html>
<head>
<script>
function readfile() {
    alert(document.getElementById('iframe').contentDocument.body.firstChild.innerHTML);
}
</script>
</head>
<body>
<iframe id='iframe' src = 'test.txt' onload='readfile()'> </iframe>
<h1>Hello World!</h1>
</body>
</html>

The file test.txt off course has to exist in the same directory as the above html file itself.

0
4

Normally, it is not possible and would be a security issue.
How ever, if you use some plugins (ActiveX, FF extensions etc) they may enable you to do so.
There is also the subject of local storage you can use with the most newer browsers.

From your comments, I am wondering why not using PHP/Ruby any other server side language to do so? They are tailored just for that.

6
  • 3
    Why is it a security issue for a local html file to access a local text file? Commented Jun 18, 2011 at 15:14
  • 2
    How would you distinguish local from external? What would stop me from "putting" a HTML file on your machine, hence forth it is local? Commented Jun 18, 2011 at 15:17
  • I was wondering if this case is different as the html file is coming from the same directory as the file I would like to read/write. So they are from the same source or the same url. Not sure, if this is right, just guessing...
    – gyurisc
    Commented Jun 18, 2011 at 15:20
  • It could read the file, but not write it if it was running in a browser. I've never used it, but doesn't JScript also allow for local read/write if run in a certain way? Commented Jun 18, 2011 at 15:24
  • 1
    Also, if someone has access to put a file on your local machine and then got you to run it, that would be the permission issue, not the HTML file itself. Commented Jun 18, 2011 at 15:25
1

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.....
1
  • Before you down vote me.. this is the only answer that fulfills the requirements of the question read/write. It is valid regardless of your contempt for IE. Commented Apr 24, 2020 at 21:00
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.