Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file from directory sorting date modified in Node JS

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.

like image 460
sagusara Avatar asked Jun 09 '15 09:06

sagusara


1 Answers

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);
like image 112
Gaurav Gandhi Avatar answered Oct 22 '22 15:10

Gaurav Gandhi