DEV Community

Cover image for How to get the creation time of the file synchronously using Node.js?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get the creation time of the file synchronously using Node.js?

Originally posted here!

To get the creation time of a file synchronously, you can use the statSync() method from the fs (filesystem) module and then use the birthtime 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 time of creation. Here you can use the fs.statSync() method and pass:

  • the path to the file as an argument.
  • the method returns a stats object where we can use the property called birthtime to get the creation time.

The birthtime property returns a valid Date object in JavaScript

It can be done like this,

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

// using fs.statSync() method to get all stats
const stats = fs.statSync("./myFile.txt");

// get creation time of the file
const creationTime = stats.birthtime;

console.log("File created at: ", creationTime); // File created at:  2021-04-30T23:53:07.633Z
Enter fullscreen mode Exit fullscreen mode

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");

// using fs.statSync() method to get all stats
const stats = fs.statSync("./myFile.txt");

// get creation time of the file
const creationTime = stats.birthtime;

console.log("File created at: ", creationTime.toUTCString()); // File created at: Fri, 30 Apr 2021 23:53:07 GMT
Enter fullscreen mode Exit fullscreen mode

That's it! 😀

Feel free to share if you found this useful 😃.


Top comments (0)