For a given directory, how can I get a list of files in chronological order (by date-modified) in Node.JS? I didn't see anything in the File System docs.
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; });
Have you tried fs.readdir()
?