HomeTutorsContact

How to get last modified date of a file using Node.js?

By Gulshan Saini
Published in NodeJS
May 26, 2020
1 min read

Node.js fs i.e. file system module allows interacting with the file system on your computer or server. All the file system operations support synchronous and asynchronous methods.

To get the last modified date of a file or directory, Node.js provides the following operations

  • fs.stat - asynchronous operation
  • fs.statSync - synchronous operation

Using fs.stat

fs.stat is an asynchronous operation and requires (path, callback) arguments

  • path is valid file path
  • callback takes two arguments i.e. (err, stats) where stats is fs.Stats object

Let’s see it in action

Save the above code in a file and name it index.js - make sure you change the path of the file. Open the terminal and go to the directory where index.js was saved and run

After, execution it should return following output

Out of the values returned in the previous output, mtime and mtimeMs are the ones which we are more interested in.

mtime and mtimeMs provide timestamp indicating the last time this file was modified and their value is updated when contents of file or directory are changed.

mtime returns updated date-time of a file in human-readable format whereas, mtimeMs timestamp indicates the last time this file was modified expressed in milliseconds since the POSIX Epoch.

Tip: You can even destructure the object and filter out only the properties you are interested in as follows

This would return the following output

Using fs.statSync

fs.statSync is synchronous operation that takes a file path as input and it returns fs.Stats object similar to its asynchronous counterpart as follows

Let’s see it in action

Save the above code in a file and name it index.js - make sure you change the path of the file. Open a terminal and go to the directory where index.jswas saved and run

This would return following output


Tags

#nodejs
Previous Article
How do you capitalize letters in CSS?

Gulshan Saini

Fullstack Developer

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

What is the max HTTP header size in NodeJS server?

August 17, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media