Node js get the last modified date of a File Tutorial

Node js get the last modified date of a File Tutorial

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.

Recommended Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *