The fs module provided by the Node.js allows us to interact with the file system. You can use the fs.stat() method to asynchronously get the file details including the last modified date.

All you need to do is just pass the relative or absolute file path to the fs.stat() method. This method returns an object of type fs.Stats which includes information about a file.

The fs.Stats object has two properties, mtime and ctime, that can be used to get the last modified date of a file. The mtime property returns the last modified date of data changes, and ctime returns the time when the file status was changed last time.

Here is an example:

const fs = require('fs');

// fetch file details
fs.stat('file.txt', (err, stats) => {
    if(err) {
        throw err;
    }

    // print file last modified date
    console.log(`File Data Last Modified: ${stats.mtime}`);
    console.log(`File Status Last Modified: ${stats.ctime}`);
});

Both, mtime and ctime properties, are an instance of JavaScript Date, so you can use all the date-related methods and properties to manipulate their values.

The mtime property is updated when you write data to the file. However, the value of ctime is only changed when you update the file's metadata, like the file name or access rights.

The fs.stat() method also has a synchronous counterpart called fs.statSync() that can be used to synchronously fetch the file details, like below:

const fs = require('fs');

// fetch file details
try {
    const stats = fs.statSync('file.txt');

    // print file last modified date
    console.log(`File Data Last Modified: ${stats.mtime}`);
    console.log(`File Status Last Modified: ${stats.ctime}`);
} catch (error) {
    console.log(error);
}

Take a look at how to read and write files in Node.js guide to learn more about handling files in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: