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

9

28

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?

Updraft answered 22/2, 2010 at 19:45 Comment(0)
F
5

Using the modern fetch method:

var lastMod = null;
fetch(xmlPath).then(r => {
    lastMod = r.headers.get('Last-Modified');
    return r.text();
})
Freberg answered 7/7, 2021 at 5:23 Comment(3)
I had to put this in an async method, so I had to await fetch(xmlPath)..., and also move the return statement outside of the fetch(): return lastModPolitical
Credit to @FutureBoy--reformatted into a separate answer due to comment limitations on code blocks.Baptize
{method: "HEAD"} is sufficient for the header.Barfly
A
39

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'));
Accrue answered 22/2, 2010 at 20:45 Comment(0)
S
8

This seems to be useful, and works for me - giving you the 'local' date

document.lastModified 

Compared to the above selection of req.getResponseHeader() it's one less round trip/http call.

Septuple answered 14/3, 2018 at 20:6 Comment(1)
This gives last modified of the current document. kennebec's solution gives last modified of an arbitrary file you have the URL to.Gelinas
F
5

Using the modern fetch method:

var lastMod = null;
fetch(xmlPath).then(r => {
    lastMod = r.headers.get('Last-Modified');
    return r.text();
})
Freberg answered 7/7, 2021 at 5:23 Comment(3)
I had to put this in an async method, so I had to await fetch(xmlPath)..., and also move the return statement outside of the fetch(): return lastModPolitical
Credit to @FutureBoy--reformatted into a separate answer due to comment limitations on code blocks.Baptize
{method: "HEAD"} is sufficient for the header.Barfly
B
4

Formatting FutureBoy's answer as a full function and adding a HEAD method and date conversion, the code would appear as follows.

function fetchLastModified(url, callback) {
    fetch(url, {method: "HEAD"})
        .then(r => {callback(new Date(r.headers.get('Last-Modified')))});
}

HEAD reduces the amount of data transmitted to just include the HTTP headers. Since FutureBoy's answer just used the headers, I wrote the function to only pull the headers. See Mozilla.org's HEAD documentation.

Baptize answered 31/12, 2022 at 5:40 Comment(1)
Don't tell me down here, update your answer.Pros
L
2

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}`);
Liaoyang answered 18/8, 2019 at 2:12 Comment(0)
D
0

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.

Deirdre answered 22/2, 2010 at 19:49 Comment(0)
I
0

I'm relatively new at JS, so I've had a hard time following the above answers to produce something workable. I finally did create something based off of Kennebec's answer above, but promptly received a dire warning from Chrome that calling XMLHttpRequest() synchronously is now deprecated, and will soon result in a script-crashing error.

So here's a plug-and-play script that will give you the modification time of a file on your server, gloriously asynchronous and compliant:

let file = "../yourfile.html";

function makeRequest(url) {
    return new Promise(function (resolve, reject) {
        let xhr = new XMLHttpRequest();
        let rand = Math.floor(Math.random() * (99999 - 11111) + 11111);
        let newurl = url+"?v="+rand;
        xhr.open("HEAD", newurl);
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                resolve(xhr.getResponseHeader("Last-Modified"));
            } else {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            }
        };
        xhr.onerror = function () {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        };
        xhr.send();
    });
}

document.onload = rando();

async function rando(){
    let result = await makeRequest(file);
    let time = Date.parse(result)/1000;
    console.log(time);
}

Hope this helps save some time.

Incidentally, the reason I needed this script was to append a variable to dynamically-loaded CSS stylesheets. By using the modification time as the variable, it prevents the browser from caching the damn stylesheets if they've been modified since the last load. This is also a well-known trick for cache busting HTML files, but it's a lot easier to do in PHP!

Infinitude answered 26/10, 2023 at 19:38 Comment(1)
XMLHttpRequest is outdated and comes from the Internet Explorer era. Fetch is the modern standard which can also be used with async and await functions.Pumice
T
0

To get the last modified date for a set of files, iterate through the individual timestamps and retun the latest. Obviously also works for a single file when passing in just a single item.

const ns = {
  files: ['/index.html', '/sw.js', '/style.css'], //sample set of typical client files
  last_mod: async(f = []) => {
    let ts = 0;
    for (let i of f) {
      let d = await fetch(i) //get each file
        .then(r => r.headers.get('Last-Modified')) //get last modified date in raw text format
        .catch(e => console.error(e));
      ts = Math.max(ts, +new Date(d)); //latest timestamp
    }
    return ts;
  }
}

console.log('Client last modified:', new Date(await ns.last_mod(ns.files)));
Tva answered 5/12, 2023 at 11:43 Comment(0)
F
-2

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

Francesfrancesca answered 22/2, 2010 at 19:46 Comment(1)
But you can send an AJAX request to a server-side process to get the info you need within JavaScript.Whitehead

© 2022 - 2025 — McMap. All rights reserved.