How to get the last modified Date of a File in Node.js

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. How to get the last modified Date of a File in Node.js
  2. Getting the last modified time in Seconds
  3. Getting the last modified time in Milliseconds
  4. Get the last modified Date of a File Asynchronously in Node.js
  5. Using async/await to get the last modified date of a file in Node.js

# How to get the last modified Date of a File in Node.js

To get the last modified date of a file in Node.js:

  1. Use the fs.statSync() method to get a stats object that stores information about the file.
  2. Access the mtime property on the stats object to get the last modified date.
index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() syntax // const fs = require('fs') function getLastModifiedDate(filepath) { const stats = fs.statSync(filepath); console.log(stats); return stats.mtime; } console.log(getLastModifiedDate('./example.txt'));

get last modified date of file in node js

The code for this article is available on GitHub

You can also use a try/catch statement if you need to handle a potential error.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() syntax // const fs = require('fs') function getLastModifiedDate(filepath) { try { const stats = fs.statSync(filepath); console.log(stats); return stats.mtime; } catch (err) { console.log(err); } } console.log(getLastModifiedDate('./example.txt'));

Make sure to pass the complete path to the file to the getLastModifiedDate() function (including the file's extension).

The code sample assumes that you have an example.txt file that's located in the same directory as your index.js file.

example.txt
bobbyhadz.com

We passed the path to the file to the fs.statSync method.

The method returns a stats object on which we can access the mtime property.

shell
Stats { dev: 66306, mode: 33204, nlink: 1, uid: 1000, gid: 1000, rdev: 0, blksize: 4096, ino: 10646214, size: 13, blocks: 8, atimeMs: 1684322963660.5115, mtimeMs: 1684322963648.5115, ctimeMs: 1684322963648.5115, birthtimeMs: 1684322960488.5198, atime: 2023-05-17T11:29:23.661Z, mtime: 2023-05-17T11:29:23.649Z, ctime: 2023-05-17T11:29:23.649Z, birthtime: 2023-05-17T11:29:20.489Z }

The mtime property is the "Modified Time" of the file - the time when the file was last modified.

The stats object also has the following properties:

  • atime - "Access Time" - the time when the file's data was last accessed.
  • ctime - "Change Time" - the time when the file's status was last changed (e.g. by chmod, chown, link, rename, unlink, read, write etc).
  • birthtime - "Birth Time" - the time when the file was created.
index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() syntax // const fs = require('fs') const stats = fs.statSync('./example.txt'); console.log(stats); // โœ… Get last modified date const lastModified = stats.mtime; console.log('last modified:', lastModified); // โœ… Get the last accessed time const lastAccessed = stats.atime; console.log('last accessed:', lastAccessed); // โœ… Get the last time when the file's status changed const lastStatusChange = stats.ctime; console.log('last status change:', lastStatusChange); // โœ… Get the file's creation time const fileCreatedAt = stats.birthtime; console.log('file created at:', fileCreatedAt);

accessing different properties on the stats object

The code for this article is available on GitHub

The code sample assumes that you have an example.txt file that's located in the same directory as your index.js file.

example.txt
bobbyhadz.com

The code samples above use the ES6 modules import/export syntax when importing the fs module.

If you use the CommonJS require() syntax, use the following import statement instead.

index.js
// ๐Ÿ‘‡๏ธ using CommonJS require() syntax const fs = require('fs')

# Getting the last modified time in Seconds

If you need to get the last time the file was modified in seconds, use the following code sample.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() syntax // const fs = require('fs') function getLastModifiedTimeInSeconds(filepath) { const stats = fs.statSync(filepath); return Math.round((new Date().getTime() - stats.mtime) / 1000); } console.log(getLastModifiedTimeInSeconds('./example.txt'));

get last modified time of file in seconds

The code for this article is available on GitHub

# Getting the last modified time in Milliseconds

If you need to get the last modified time of the file in milliseconds, use the mtimeMs property instead.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() syntax // const fs = require('fs') function getLastModifiedTimeInMs(filepath) { const stats = fs.statSync(filepath); return Math.round(stats.mtimeMs); } console.log(getLastModifiedTimeInMs('./example.txt'));

The mtimeMs property returns a timestamp that indicates the last time the given file was modified in milliseconds since the POSIX epoch.

get last modified time of file in milliseconds

# Get the last modified Date of a File Asynchronously in Node.js

The previous examples used the statSync method to get the last modified date of a file synchronously, however, you can also achieve the same asynchronously.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() syntax // const fs = require('fs') fs.stat('example.txt', (error, stats) => { if (error) { console.log(error); } console.log(stats); // โœ… Get last modified time const lastModified = stats.mtime; console.log('last modified:', lastModified); // โœ… Get last time the file was accessed const lastAccessed = stats.atime; console.log('last accessed:', lastAccessed); // โœ… Get the last time the file's status changed const lastStatusChange = stats.ctime; console.log('last status change:', lastStatusChange); // โœ… Get the time the file was created const fileCreatedAt = stats.birthtime; console.log('file created at:', fileCreatedAt); });

get last modified date of file asynchronously

The code for this article is available on GitHub

We passed a file path and a callback function to the fs.stat() method.

The code sample above assumes that you have an example.txt file located in the same directory as your index.js file.

example.txt
bobbyhadz.com

Make sure to specify the complete file path (including the extension).

The callback function gets passed 2 arguments - an error and the stats object.

The error argument is going to be null if no error occurred.

We accessed the mtime property on the stats object to get the last modified time.

index.js
const lastModified = stats.mtime; console.log('last modified:', lastModified);

# Using async/await to get the last modified date of a file in Node.js

You can also use the util.promisify() method to promisify the fs.stat() method to be able to use the async/await syntax.

index.js
import fs from 'fs'; import util from 'util'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() syntax // const fs = require('fs') // const util = require('util') async function getLastModifiedDate(filepath) { const statPromise = util.promisify(fs.stat); try { const stats = await statPromise(filepath); // โœ… Get last modified time const lastModified = stats.mtime; console.log('last modified:', lastModified); // โœ… Get last time the file was accessed const lastAccessed = stats.atime; console.log('last accessed:', lastAccessed); // โœ… Get the last time the file's status changed const lastStatusChange = stats.ctime; console.log('last status change:', lastStatusChange); // โœ… Get the time the file was created const fileCreatedAt = stats.birthtime; console.log('file created at:', fileCreatedAt); return stats.mtime; } catch (err) { console.log(err); } } getLastModifiedDate('./example.txt');

using async await to get last modified date of file

The code for this article is available on GitHub

The util.promisify() method takes a function that follows the error-fist callback style and returns a version of that function that returns a Promise.

index.js
const statPromise = util.promisify(fs.stat);

We used the async/await syntax to await the Promise.

index.js
const stats = await statPromise(filepath); // โœ… Get last modified time const lastModified = stats.mtime; console.log('last modified:', lastModified);

The last step is to access the last modified time of the file using the mtime property.

If you need to get the last time the file's status changed, use the ctime property instead.

index.js
const stats = await statPromise(filepath); // โœ… Get the last time the file's status changed const lastStatusChange = stats.ctime; console.log('last status change:', lastStatusChange);

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev