25

Need to read list of files from particular directory with Date modified by descending or ascending in Node js.

I have tried below code but could not get the solution.

fs.readdir(path, function (err, files) {
                    if (err) throw err;
                    else {
                        var res = [];
                        files.forEach(function (file) {
                            if (file.split('.')[1] == "json") {
                                fs.stat(path, function (err, stats) {                                                                  

                                });
                                res.push(file.substring(0, file.length - 5));
                            }
                        });
                    }  

stats parameter give mtime as modified time?

Is there any way to get files with modified date.

Atul
  • 3,778
  • 5
  • 47
  • 87
sagusara
  • 383
  • 1
  • 3
  • 9
  • Flagged as a duplicate of [Using Node.JS, how do you get a list of files in chronological order?](https://stackoverflow.com/questions/10559685/using-node-js-how-do-you-get-a-list-of-files-in-chronological-order), hopefully can merge the two – AncientSwordRage Jan 02 '22 at 23:36

3 Answers3

71

mtime gives Unix timestamp. You can easily convert to Date as,
const date = new Date(mtime);

And for your sorting question, you can do as following

var dir = 'mydir/';

fs.readdir(dir, function(err, files){
  files = files.map(function (fileName) {
    return {
      name: fileName,
      time: fs.statSync(dir + '/' + fileName).mtime.getTime()
    };
  })
  .sort(function (a, b) {
    return a.time - b.time; })
  .map(function (v) {
    return v.name; });
});  

files will be an array of files in ascending order.
For descending, just replace a.time with b.time, like b.time - a.time

UPDATE: ES6+ version

const myDir = 'mydir';

const getSortedFiles = async (dir) => {
  const files = await fs.promises.readdir(dir);

  return files
    .map(fileName => ({
      name: fileName,
      time: fs.statSync(`${dir}/${fileName}`).mtime.getTime(),
    }))
    .sort((a, b) => a.time - b.time)
    .map(file => file.name);
};

getSortedFiles(myDir)
  .then(console.log)
  .catch(console.error);
Zac Anger
  • 6,983
  • 2
  • 15
  • 42
Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
0

The solution with the streams works well. But incase you do not want to use streams, you may use statsSync as follows:

 //import the fs
const fs = require("fs");

//list with statSync
//I added letters at the start of the files names so that the alphabetical order becomes different from the chronollogical
fs.readdir("./anville95/", (error, files) => {
    if(error) {
        console.log("Sorry lad, I was unable to read the files!");
        return;
    }
    console.log("Before sorting with the last modification time...");
    console.log(files);
    //compare each file with each and every file using their milliseconds modification time and swap if necessary
    for(var i = 0; i < files.length; i++) {
        for(var j = 0; j < files.length; j++) {
            //create the stats files
            var firstFileStats = fs.statSync("./anville95/" + files[i]);
            var secondFileStats = fs.statSync("./anville95/" + files[j]);
            //if files[i] comes before files[j] and files[i] modification time is older than files[j] modification time, swap them
            if(i < j && firstFileStats.mtimeMs > secondFileStats.mtimeMs) {
                var swap = files[i];
                files[i] = files[j];
                files[j] = swap;
            }
        }
    }
    //At this point, the swapping is done thus I print out the results
    console.log("After sorting chronollogically with statSync().mtimeMs...");
    console.log(files);
});

Here are the screenshots I took of my results during its execution. Thank you for reading, happy coding.

The screenshot. Thank you for reading, happy coding

anville95
  • 21
  • 5
-4

I have got the answer using sorting operation.

fs.stat(path, function (err, stats) {
                        res.push(file.substring(0, file.length - 5) + '&' + stats.mtime);
                    });

stored mtime to an array and sort that array using sorting technique in below url.

Simple bubble sort c#

Community
  • 1
  • 1
sagusara
  • 383
  • 1
  • 3
  • 9