Using Node.JS, how do you get a list of files in chronological order?

Solution 1:

Give this a shot.

var dir = './'; // your directory

var files = fs.readdirSync(dir);
files.sort(function(a, b) {
               return fs.statSync(dir + a).mtime.getTime() - 
                      fs.statSync(dir + b).mtime.getTime();
           });

I used the "sync" version of the methods. You should make them asynchronous as needed. (Probably just the readdir part.)


You can probably improve performance a bit if you cache the stat info.

var files = fs.readdirSync(dir)
              .map(function(v) { 
                  return { name:v,
                           time:fs.statSync(dir + v).mtime.getTime()
                         }; 
               })
               .sort(function(a, b) { return a.time - b.time; })
               .map(function(v) { return v.name; });

Solution 2:

2021, async/await using fs.promises

const fs = require('fs').promises;
const path = require('path');

async function readdirChronoSorted(dirpath, order) {
  order = order || 1;
  const files = await fs.readdir(dirpath);
  const stats = await Promise.all(
    files.map((filename) =>
      fs.stat(path.join(dirpath, filename))
        .then((stat) => ({ filename, mtime: stat.mtime }))
    )
  );
  return stats.sort((a, b) =>
    order * (b.mtime.getTime() - a.mtime.getTime())
  ).map((stat) => stat.filename);
}

(async () => {
  try {
    const dirpath = __dirname;
    console.log(await readdirChronoSorted(dirpath));
    console.log(await readdirChronoSorted(dirpath, -1));
  } catch (err) {
    console.log(err);
  }
})();

Solution 3:

a compact version of the cliffs of insanity solution

function readdirSortTime(dir, timeKey = 'mtime') {
  return (
    fs.readdirSync(dir)
    .map(name => ({
      name,
      time: fs.statSync(`${dir}/${name}`)[timeKey].getTime()
    }))
    .sort((a, b) => (a.time - b.time)) // ascending
    .map(f => f.name)
  );
}