Dave
Dave

Reputation: 189

Alternative to setInterval to see if file has been modified?

I'm trying to see if a file has been modified on the server. Currently, I've got setInterval checking every second. It's using AJAX to call a PHP script that checks the file length against what the JS thinks it should be. My question is, is there a better/more efficient way to do this?

(I'm using a mutationObserver for something else and it got me wondering if there is something else similar that could help with this...)

JS:

function checkFile() {
var fReader = new XMLHttpRequest();
var params = "MODE=CHECK&File=Data.txt";

fReader.open("POST","File.php",false);

fReader.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fReader.setRequestHeader("Content-length", params.length);
fReader.setRequestHeader("Connection", "close");

fReader.send(params);

return JSON.parse(fReader.responseText).CHECK > myLength;
}

PHP:

switch($MODE) {

    case('CHECK'):
        if(file_exists($_POST['File'])){
            $return['CHECK'] = count(file($_POST['File']));
        }
        break;
    case('GET'):

        $lines = file($_POST['File']);
        $length=$_POST['LEN'];#This is the number of lines JS has.

        $count = count($lines);

        if ($length < $count) {
            $return['GET'] = array_slice($lines,$length);
        } else {
            #return all lines.
            $return['GET'] = $lines;
        }
        break;

...

}
echo json_encode($return);

The only other idea I had was to have AJAX check the file asynchronously and split out the response to a separate function. The JS will send over a file count (in the params) and the PHP will check that against the count. If its different, it returns the difference, otherwise it returns something like null or "no change". Currently, i'm checking the file as above. If it's changed, i AJAX again with mode GET to actually get the changes...

Ideas? Completely different approach? I'm open to unconventional approaches. (my browser of choice is Chrome, I'm using an extension already, so i could do something in there as well...).

Thanks, Dave

Upvotes: 1

Views: 332

Answers (1)

Tibos
Tibos

Reputation: 27823

What you are using is called polling. You ask the server repeatedly if something changed. A better solution is long-polling. You ask the server once and the server returns only when something changed. An even better solution could be web sockets. For now you should focus on the long-polling solution.

About long-polling:

The trick is in the server's implementation which doesn't return until the file has changed. For your server to decide if the file has changed you can also use polling in a while loop, but the advantage is that there is no network traffic. There may be other ways to get the state of the file using PHP, at the very least you turned your problem from checking the state of a remote file to checking it locally.

Upvotes: 2

Related Questions