Node.js — Get a File’s Last Modified/Updated Date

Code Sample

The file system module in Node.js provides all file-related functions. You can fetch file details with a so called “stats” instance. A part of the “stats” instance is a file’s last modified date.

Node.js Series Overview

Last Modified Date of a File

Retrieve a stats instance of a given file including meta data with the fs module in Node.js.

In Node.js you’ll find the file’s last modified date split in two dates: file data and status. The last modified date for data changes is available in the mtime property of the stats object. The last modified date for file status changes lives in ctime:

const Fs = require('fs')

function lastUpdatedDate (file) {  
  const { mtime, ctime } = Fs.statSync(file)

  console.log(`File data   last modified: ${mtime}`)
  console.log(`File status last modified: ${ctime}`)

  return mtime
}

lastUpdatedDate('./file.txt')  

Both, mtime and ctime, are JavaScript Date instances with all the date-related methods and properties.

The mtime changes when the file data updates, for example writing to the file. Changes to the ctime apply when changing the file‘s meta data, like the file name or access rights (chmod/chown).

Notice that there are mtimeMs and ctimeMs properties in the stats object holding the dates in milliseconds.

Enjoy coding & make it rock!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.