How to read file from directory sort date changed in Node JS

You need to read a list of files from a specific directory with date modified in descending or ascending order in Node js .

I tried the code below but couldn't get a 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));
                            }
                        });
                    }  

      

statistic parameter gives mtime as modified time?

Is there a way to get the files with the changed date.

+3


source to share


2 answers


mtime

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

And for your sorting question, you can do the 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

there will be an array of files in ascending order.
For descent, just replace a.time

with b.time

, for exampleb.time - a.time

+3


source


I have an answer using a sort operation.

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

      



stores the mtime in an array and sorts that array using the sort method in the bottom url.

Simple bubble sorting c #

-1


source







All Articles