The fs module provided by 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 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 last time the file status was changed.

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 instances 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)
}

Read this 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.