jmoon
jmoon

Reputation: 576

Finding latest modified file in a folder

How do I go through a folder and find out which is the newest created/modified file and put the full path of it into a var as string?

Haven't really figured out io/best practices for io

Upvotes: 3

Views: 12154

Answers (5)

AmirabbasGhasemi
AmirabbasGhasemi

Reputation: 309

I think this is a better and faster choice.

fs.readdir(".",function(err, list){
    console.log(list[(list.length-1)])
})

Upvotes: 1

techlab.fze
techlab.fze

Reputation: 11

In order to download the latest file according to name and other stuff:

//this function runs a script
//this script exports db data
// and saves into a directory named reports
router.post("/download", function (req, res) {

//run the script
  var yourscript = exec("./export.sh", (error, stdout, stderr) => {
    console.log(stdout);
    console.log(stderr);
  });
//download latest file
  function downloadLatestFile() {
//set the path
    const dirPath = "/Users/tarekhabche/Desktop/awsTest/reports";
//get the latest created file
    const lastFile = JSON.stringify(getMostRecentFile(dirPath));
//parse the files name since it contains a date

    fileDate = lastFile.substr(14, 19);
    console.log(fileDate);
//download the file
    const fileToDownload = `reports/info.${fileDate}.csv`;
    console.log(fileToDownload);
    res.download(fileToDownload);
  }
// download after exporting the db since export takes more time
  setTimeout(function () {
    downloadLatestFile();
  }, 1000);
});
//gets the last file in a directory

const getMostRecentFile = (dir) => {
  const files = orderRecentFiles(dir);
  return files.length ? files[0] : undefined;
};
//orders files accroding to date of creation
const orderRecentFiles = (dir) => {
  return fs
    .readdirSync(dir)
    .filter((file) => fs.lstatSync(path.join(dir, file)).isFile())
    .map((file) => ({ file, mtime: fs.lstatSync(path.join(dir, file)).mtime }))
    .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
};
const dirPath = "reports";
getMostRecentFile(dirPath);

Upvotes: 0

btargac
btargac

Reputation: 402

Lets say you want to get the most recent file in a directory and send it to the client who wants to get a non-existent file in a folder. For example if your static middleware can't serve the file and automatically calls next() function.

You can use the glob module to get the list of files that you want to search, then reduce them in a function;

// handle non-existent files in a fallthrough middleware
app.use('/path_to_folder/', function (req, res) {
    // search for the latest png image in the folder and send to the client
    glob("./www/path_to_folder/*.png", function(err, files) {
        if (!err) {

            let recentFile = files.reduce((last, current) => {

                let currentFileDate = new Date(fs.statSync(current).mtime);
                let lastFileDate = new Date(fs.statSync(last).mtime);

                return ( currentFileDate.getTime() > lastFileDate.getTime() ) ? current: last;
            });

            res.set("Content-Type", "image/png");
            res.set("Transfer-Encoding", "chunked");
            res.sendFile(path.join(__dirname, recentFile));
        }
    });

Upvotes: 0

LasaleFamine
LasaleFamine

Reputation: 633

The Brad's snippet works (and is awesome, thanks) well when the files are in the same directory, but if you are checking another folder you need to resolve the path for the statSync param:

const fs = require('fs');
const {resolve, join} = require('path');

fs.readdir(resolve('folder/inside'),function(err, list){
    list.forEach(function(file){
       console.log(file);
       stats = fs.statSync(resolve(join('folder/inside', file)));
       console.log(stats.mtime);
       console.log(stats.ctime);
    })
})

Upvotes: 5

Brad Cunningham
Brad Cunningham

Reputation: 6501

Take a look at http://nodejs.org/api/fs.html#fs_class_fs_stats

look at the ctime or mtime to find the created and modified time.

Something like this:

var fs = require('fs');

fs.readdir(".",function(err, list){
    list.forEach(function(file){
        console.log(file);
        stats = fs.statSync(file);
        console.log(stats.mtime);
        console.log(stats.ctime);
    })
})

loops the current directory (.) and logs the file name, grabs the file stats and logs the modified time (mtime) and create time (ctime)

Upvotes: 6

Related Questions