finding the latest modified file in a folder in javascript

Here is a way to find the latest modified file in a folder using JavaScript and Node.js:

index.tsx
const fs = require('fs');
const path = require('path');

function getLatestModifiedFile(folderPath) {
    // Read the directory's content
    const files = fs.readdirSync(folderPath);

    // Variable to store the latest modified file information
    let latestFile = {
        name: '',
        modified: 0
    };

    // Loop through each file in the folder
    files.forEach(file => {
        const filePath = path.join(folderPath, file);

        // Get the file's stats
        const fileStats = fs.statSync(filePath);

        // Check if this file is more recently modified than the previous latest
        if (fileStats.mtimeMs > latestFile.modified) {
            latestFile = {
                name: file,
                modified: fileStats.mtimeMs
            };
        }
    });

    return latestFile.name;
}

// Example usage
const folderPath = './folder';
const latestFile = getLatestModifiedFile(folderPath);

console.log(`The latest modified file in "${folderPath}" is "${latestFile}".`);
1008 chars
38 lines

This code uses the fs (file system) module of Node.js to read the directory's content and get the stats (including modification time) of each file. It then compares the modification time of each file to find the latest modified file. The function getLatestModifiedFile returns the name of the latest modified file.

related categories

gistlibby LogSnag