In this tutorial, you will learn how to get the last modified date time of the file in node js using the fs module
, fs.promises.stat
, util.promisify
method.
How to get the last modified date of a File in Node js
Here are some methods to get the last modified date time of the file:
Method 1: Using fs.stat
Using the fs.stat
method, you can get detailed information about a file:
const fs = require('fs');
const filePath = 'path/to/your/file.txt'; // Replace with your file's path
fs.stat(filePath, (err, stats) => {
if (err) {
console.error('Error:', err);
return;
}
const lastModified = stats.mtime; // mtime is the last modified date
console.log('Last modified:', lastModified);
});
Method 2: Using fs.promises.stat
(Node.js 10+)
If you prefer working with Promises, you can use the fs.promises.stat
method, available in Node.js versions 10 and above:
const fs = require('fs').promises; const filePath = 'path/to/your/file.txt'; (async () => { try { const stats = await fs.stat(filePath); const lastModifiedDate = stats.mtime; // Get the last modified date console.log(`Last modified date: ${lastModifiedDate}`); } catch (err) { console.error(err); } })();
Method 3: Using the util.promisify
method (Node.js 8+)
For Node.js versions 8 and above, you can also use the util.promisify
method to convert the callback-based fs.stat
function into a Promise-based one:
const fs = require('fs');
const util = require('util');
const stat = util.promisify(fs.stat);
const filePath = 'path/to/your/file.txt';
(async () => {
try {
const stats = await stat(filePath);
const lastModifiedDate = stats.mtime; // Get the last modified date
console.log(`Last modified date: ${lastModifiedDate}`);
} catch (err) {
console.error(err);
}
})();
Conclusion
That’s it; you have learned how to get the last modified date time of file in node js using fs module, fs.promises.stat
, util.promisify
method.