19

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.

Gaurav Gandhi
  • 2,796
  • 2
  • 24
  • 38
sagusara
  • 327
  • 1
  • 2
  • 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

2 Answers2

59

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

Promise.resolve()
  .then(() => getSortedFiles(myDir))
  .then(console.log)
  .catch(console.error);
Gaurav Gandhi
  • 2,796
  • 2
  • 24
  • 38
-2

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
  • 327
  • 1
  • 2
  • 9