Sometimes, we want to get a file’s last modified date in Node.js
In this article, we’ll look at how to get a file’s last modified date in Node.js.
How to get a file’s last modified date in Node.js?
To get a file’s last modified date in Node.js, we can use the fs.stat
or fs.statSync
method.
For instance, we write
fs.stat("/dir/file.txt", (err, stats) => {
const {
mtime
} = stats;
console.log(mtime);
});
to call fs.stat
with the path of the file that we want to get the last modified date for asynchronously.
And we get the last modified date of the file with the mtime
property from the stats
object in the callback.
We can do the same thing synchronously with statSync
:
const stats = fs.statSync("/dir/file.txt");
const {
mtime
} = stats;
console.log(mtime);
We call statSync
with the path of the file and the stats
are returned synchronously.
Conclusion
To get a file’s last modified date in Node.js, we can use the fs.stat
or fs.statSync
method.