Fetch last modified timestamp from a file in Node.js

Published Saturday, January 16, 2021

Jonas Arnklint
@arnklint

I was recently tasked with building a tiny file caching function, it would read cached data from a file if the cache was modified less than 5 minutes ago. But in order to to do so, we of course needed to find the last modified timestamp on that file. This is how to retreive the last modified timestamp on a file in Node.js.

There is one easy way of reading the meta information on a file, and that is using fs.stat and its synchronous friend fs.statSync. It takes a file path and returns its meta information including the last modified date.

this is my code 411

I decided to create this utility function to be able to use it in other areas of the system. It simply runs the fs.stat function and returns ths mtime from the stats object. The fs.statSync returns other properties to indicate when the file was created and what size the file you're targeting has as well and is useful in general to retreive any meta information about a file in the file system.

You can also use the fs.stat function to find out file size.