Is it possible to retrieve the last modified date of a file using Javascript?

Viewed 36361

I have a set of links on a web page that link to PDF forms and .doc forms. These files are not stored in a database, simply stored as they are, locally on the server. Is it possible to retrieve the last modified date of a PDF or DOC file using Javascript? I don't have any specific need to use Javascript, but it is preferable.

UPDATE: Now that I realize that Javascript can't access the filesystem, is there an alternative method?

6 Answers

If it's on the same server as your calling function you can use XMLHttpRequest-

This example is not asynchronous, but you can make it so if you wish.

function fetchHeader(url, wch) {
    try {
        var req=new XMLHttpRequest();
        req.open("HEAD", url, false);
        req.send(null);
        if(req.status== 200){
            return req.getResponseHeader(wch);
        }
        else return false;
    } catch(er) {
        return er.message;
    }
}

alert(fetchHeader(location.href,'Last-Modified'));

Using the modern fetch method:

var lastMod = null;
fetch(xmlPath).then(r => {
    lastMod = r.headers.get('Last-Modified');
    return r.text();
})

File.lastModified

You can use the File.lastModified property to obtain the last modified date of a file as the number of milliseconds since the Unix epoch.

Example:

const file = document.getElementById('input').files[0];
const lastModifiedDate = new Date(file.lastModified);

console.log(`Last Modified Date: ${lastModifiedDate}`);

If an interface is exposed through HTTP, you can. Another way of saying: expose a WebService end-point to gain access to this information.

Of course, you can't have direct access to the filesystem for security reasons.

No, it's not. You can't access the file system through JavaScript

Related