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

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


Give this a shot.

var dir = './'; // your directoryvar 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; });


Async version (2018)

const fs = require('fs');const path = require('path');const util = require('util');const readdirAsync = util.promisify(fs.readdir);const statAsync = util.promisify(fs.stat);async function readdirChronoSorted(dirpath, order) {  order = order || 1;  const files = await readdirAsync(dirpath);  const stats = await Promise.all(    files.map((filename) =>      statAsync(path.join(dirpath, filename))        .then((stat) => ({ filename, stat }))    )  );  return stats.sort((a, b) =>    order * (b.stat.mtime.getTime() - a.stat.mtime.getTime())  ).map((stat) => stat.filename);}(async () => {  try {    const dirpath = path.join(__dirname);    console.log(await readdirChronoSorted(dirpath));    console.log(await readdirChronoSorted(dirpath, -1));  } catch (err) {    console.log(err);  }})();


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