So I\'ve got this local file named \'data.json\' containing various data. I want to refresh my page only when some data in the json file changes. Appreciate your help if you
Well, first, you have to trigger an event or something when the file changes. Some information about that can be found here: Check if file has changed using HTML5 File API
(Copied from the link) Something like that should do the job:
(function() {
var input;
var lastMod;
document.getElementById('btnStart').onclick = function() {
startWatching();
};
function startWatching() {
var file;
if (typeof window.FileReader !== 'function') {
display("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('filename');
if (!input) {
display("Um, couldn't find the filename element.");
}
else if (!input.files) {
display("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
display("Please select a file before clicking 'Show Size'");
}
else {
file = input.files[0];
lastMod = file.lastModifiedDate;
display("Last modified date: " + lastMod);
display("Change the file");
setInterval(tick, 250);
}
}
function tick() {
var file = input.files && input.files[0];
if (file && lastMod && file.lastModifiedDate.getTime() !== lastMod.getTime()) {
lastMod = file.lastModifiedDate;
alert("File changed: " + lastMod);
}
}
})();
In this case, the your problem is with the refresh. Usually a page can be refreshed using location.reload()
, but in your case, refreshing the page will lose the connection to the file (the user will have to re-select it in the file input)
If you want to update some data using the new file, just retrigger it, but I strongly recommend to not refresh the page.
However, if you do want to refresh the page entirely, you can make a kind of a "helper-app" (A background application that will read the file continously and via websocket notify the Javascript when the file has changed).
You can do something like that using Websockets or $ajax (for jQuery) or XMLHttpRequest (non jQuery).
The helper app can be written in Java, C# or Python (C# for windows only) or any other language that HTTP server or Websocket server can be implemented in.