ArticleZip > In Node Delete All Files Older Than An Hour

In Node Delete All Files Older Than An Hour

Are you looking to automate the process of deleting old files in Node.js? This tutorial will guide you through the steps to create a simple script that deletes all files in a specific directory that are older than an hour. This can be useful for cleaning up temporary files or logs that accumulate over time.

To begin, you will need to have Node.js installed on your machine. If you haven't already, you can download and install it from the official Node.js website.

Next, create a new JavaScript file, let's name it `deleteOldFiles.js`, and open it in your favorite code editor. In this file, we will write the script to delete the old files.

Start by requiring the `fs` (file system) module, which is built into Node.js and provides functions for interacting with the file system. Add the following line at the top of your file:

Javascript

const fs = require('fs');

Next, define the directory path where you want to delete the old files. For example, if you want to delete files in a directory named `logs`, you can set the directory path as follows:

Javascript

const directoryPath = './logs';

Now, let's write the main logic of our script. We will use the `fs.readdirSync()` function to read the contents of the directory, and then loop through each file to check its last modified time. If a file's last modified time is older than an hour, we will delete it using the `fs.unlinkSync()` function.

Javascript

fs.readdirSync(directoryPath).forEach(file => {
    const filePath = `${directoryPath}/${file}`;
    const fileStats = fs.statSync(filePath);
    const fileAge = (Date.now() - fileStats.mtime.getTime()) / 1000 / 60 / 60; // Calculate file age in hours

    if (fileAge > 1) {
        fs.unlinkSync(filePath);
        console.log(`Deleted old file: ${file}`);
    }
});

In this script, we are looping through each file in the directory, calculating its age in hours by comparing the current time with the file's last modified time. If the file is older than an hour, we delete it and log a message to the console.

You can now save the `deleteOldFiles.js` file and run it from the command line using Node.js:

Bash

node deleteOldFiles.js

After running the script, it will delete all files in the specified directory that are older than an hour. Make sure to test the script on a sample directory before using it on production data to avoid any accidental data loss.

Congratulations! You have successfully created a Node.js script to delete old files in a directory. Feel free to customize the script further based on your specific requirements. Happy coding!