How to get the last modified time of the file asynchronously using Node.js?

April 20, 2021 - 2 min read

To get the last modified time of a file asynchronously, you can use the stat() method from the fs (filesystem) module and then use the mtime property from the returned stats object in Node.js.

Let's say we have a file called myFile.txt in which you want to get the last modified time. Here you can use the fs.stat() method and pass:

  • the path to the file as the first argument.
  • a callback function that will get invoked after statistics about the file is obtained, in which the first parameter is an error object and the second parameter is the stats object which contains all the information about the file.

In our case, the last modified time of the file can be obtained using the mtime property from the stats object. The mtime property returns a valid Date object in JavaScript.

It can be done like this,

// require fs module
const fs = require("fs");

// get last modified time using fs.stat() method
fs.stat("./myFile.txt", (error, stats) => {
  // in case of any error
  if (error) {
    console.log(error);
    return;
  }

  // else show last modified time from stats object
  console.log("File last modified at: ", stats.mtime); // File last modified at:  2021-04-30T23:53:07.633Z
});

See the above code live in repl.it.

If you want to see the Date in a more human-readable way you can use the Date object methods. Let's use the toUTCString() method like this,

// require fs module
const fs = require("fs");

// get last modified time using fs.stat() method
fs.stat("./myFile.txt", (error, stats) => {
  // in case of any error
  if (error) {
    console.log(error);
    return;
  }

  // else show last modified time from stats object
  console.log("File last modified at: ", stats.mtime.toUTCString()); // File last modified at: Fri, 30 Apr 2021 23:53:07 GMT
});

That's it! 😀

Feel free to share if you found this useful 😃.