3

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

jmoon
  • 606
  • 3
  • 7
  • 18

5 Answers5

6

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)

Brad Cunningham
  • 6,402
  • 1
  • 32
  • 39
5

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);
    })
})
LasaleFamine
  • 613
  • 6
  • 12
1

I think this is a better and faster choice.

fs.readdir(".",function(err, list){
    console.log(list[(list.length-1)])
})
ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 27 '22 at 16:08
0

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));
        }
    });
btargac
  • 392
  • 2
  • 10
0

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);