How to get the last modified date of a file with Node.js

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.