1

I have a local text file which is kept changing by other programs. I want to write a html and javascript based web page to show the content of file dynamically. I have searched in google and found that most solutions require to get this text file via html element. I wonder if there is a way to get the file via a fixed path(lets say it is a string of the file directory) in javascript. I am using Javascript fileReader. Any help will be appreciated.

user3636706
  • 197
  • 1
  • 2
  • 15

4 Answers4

2

This is not possible using javascript running inside the browser. You will not be able to do anything outside the browser.

EDIT:

You could run a Node.js server though that runs on localhost and does your file operations you desire. You could build a API so your html page that you load in the browser calls your serverscript to do your file operations.

Do you understand what I mean?

Max Bumaye
  • 1,017
  • 10
  • 17
  • Yes, I understand, however my first intention is to keep it simple. I will try your approach if I found no more solution in th end. – user3636706 Dec 10 '14 at 12:37
  • Well it is not possible accessing local files from your browser -You can only access the browser API that is the reason why Billy suggested the localstorage solution. If you want controll and accessrights to your operating system you need to install something that runs javascript in OS context and not in your browser. Setting upo a nodejs server doing your tasks is almost as simple as doing them in your local html file :) – Max Bumaye Dec 10 '14 at 12:40
  • @MaxBumaye - _Well it is not possible accessing local files from your browser_ - Actually, yeah it is possible. You just have to choose them with a input element. – enhzflep Dec 10 '14 at 12:53
  • @enhzflep how do you consider the file being "local" then.. its not local if you load the document into the browser ;). The author talked about "content of file dynamically". In this case I assume the author wants to acces the file programmaticly without loading it into the browsercontext... How would the author save this document in the end on the local system – Max Bumaye Dec 10 '14 at 12:58
  • Simple - a web-page hosted on a server in Iceland can allow me to choose a file. That webpage can then reload the file I designate at regular intervals. The server knows nothing of my file - only the JS running in my browser does, yet still I see the output of a constantly changing file on my own system. How on earth could you fail to consider that a local file? As for saving, easy. Right-click the iframe, hit view source, right-click, hit save as. (Not that this functionality was requested in the original question, mind you.) – enhzflep Dec 10 '14 at 13:04
  • " a web-page hosted on a server in Iceland " - dont have to add anything to that I guess ;) – Max Bumaye Dec 10 '14 at 13:06
  • @MaxBumaye - was it really too hard to just admit you made a mistake? – enhzflep Dec 10 '14 at 13:09
  • first of all this does not meat the requirements the author has. secondly: Sorry to say this, but you are still wrong. I wonder how crazy the internet would be if any page could just access and write to your LOCAL FILE SYSTEM! Browsers simply prohibit a local file system access because its a huge securityy issue – Max Bumaye Dec 10 '14 at 13:16
  • @MaxBumaye - it seems that you don't understand the concept of a local file very well at all. Here's a thread that articulates what I've been saying the whole time. Take the time to read it - it will only be to the benefit of yourself and any future clients. http://stackoverflow.com/questions/371875/local-file-access-with-javascript – enhzflep Dec 10 '14 at 23:46
  • 1
    You must be right in some way. I just didnt get your Iceland example and when you started talking about rightclick in an I-Frame I just thought you where way of - but I do admit that there is some sort of truth to what you are saying. I havent been playing with the html5 filesystem API yet but it sure enough doesnt have to do anything with iframes and iceland :D - but it seems to be capable of doing file operations on your local system. – Max Bumaye Dec 11 '14 at 10:12
0

How much information does the text file hold, Depending on your scenario it might be worth looking into javascript localstorage W3SCHOOLS local storage. Would that help your situation ?

Billy
  • 2,448
  • 1
  • 10
  • 13
  • I dont know why but I cant open w3school pages now. The information hold by my text file is just serveral kbs. – user3636706 Dec 10 '14 at 12:36
  • local storage will store information on the users computer, it can be cleared by them if they want to. try [THIS PAGE](http://diveintohtml5.info/storage.html) – Billy Dec 10 '14 at 12:49
0

What you can do is allow the user to choose the file of interest, using a file-input. Once done, the browser wil have access to the file, even though the JS wont have access to the file's full-path.

Once the user has chosen the file, you can reload it and refresh the view pretty-much as often as you please.

Here's a short demo, using a file input (<input type='file'/>) and an iframe. You can pick pretty much anything the browser will normally display, though there are limits on the size of the file that will work - due to the limit of the length of a URL - the file's data is turned into a data-url and that url is set as the source of the iframe.

As a demo, pick a file and then load it. Now, open the file in another program and change it. Finally, press the load button once again - the new content now fills the iframe. You can trigger the loading of the file by a timer or any other event in the page. As far as I'm aware, you cannot re-load it when it changes, since there's no notification from the OS - you have to use a button, timer, element event or whatever. Basically, you have to poll for changes.

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    // uncomment this line for on-demand loading.
    byId('loadBtn').addEventListener('click', onLoadBtnClick, false);
}

// fileVar is an object as returned by <input type='file'>
// tgtElem is an <iframe> or <img> element - can be on/off screen (doesn't need to be added to the DOM)
function loadFromFile(fileVar, tgtElem)
{
    var fileReader = new FileReader();
    fileReader.onload = onFileLoaded;
    fileReader.readAsBinaryString(fileVar);
    function onFileLoaded(fileLoadedEvent)
    {
        var result,data;
        data = fileLoadedEvent.target.result;
        result = "data:";
        result += fileVar.type;
        result += ";base64,";
        result += btoa(data);
        tgtElem.src = result;
    }
}

function onLoadBtnClick(evt)
{
    var fileInput = byId('mFileInput');
    if (fileInput.files.length != 0)
    {
        var tgtElem = byId('tgt');
        var curFile = fileInput.files[0];
        loadFromFile(curFile, tgtElem);
    }
}

</script>
<style>
</style>
</head>
<body>
    <button id='loadBtn'>Load</button><input id='mFileInput' type='file'/><br>
    <iframe id='tgt'></iframe>
</body>
</html>
enhzflep
  • 12,927
  • 2
  • 32
  • 51
  • Hey, thanks a lot! Your code indeed gives me a lot help and some ideas! – user3636706 Dec 10 '14 at 13:28
  • But can I reload it automatically? lets say every 5 seconds – user3636706 Dec 10 '14 at 13:30
  • @user3636706 - sure you can. You can make a call to setInterval to start a re-occuring timer event. If you supply the name of a function that will re-load the selected file, you have a mechanism that will repeatedly update the view of the file in question. See here for the w3scools info: http://www.w3schools.com/jsref/met_win_setinterval.asp (The MDN help will almost certainly be more comprehensive) – enhzflep Dec 10 '14 at 23:50
0

you can use nodejs to watch for a filechange using watchfile module, if you just want to watch the filechange and its content. you can run following code using node, but it only consoles the file changed in your terminal.

    var fs=require('fs'); 
    fs.watchFile('message.text', function (curr, prev) { //listens to file change
            fs.readFile('message.text', function(err,data){ //reads the file
                console.log(data.toString()); //consoles the file content
            });
          });
Pravin
  • 1,671
  • 5
  • 23
  • 36