Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 681
Newtang Avatar asked May 11 '12 23:05

Newtang


People also ask

How do I sort a list in node JS?

sort() is an array function from Node. js that is used to sort a given array. Parameter: This function does not takes any parameter. Return type: The function returns the sorted array.

What is the difference between Readdir and readdirSync?

readdir(). It is the same as fs. readdirSync(), but has the callback function as the second parameter.

How to get list of all files in a directory in node?

Steps to get list of all the files in a directory in Node.js Load all the required Nodejs Packages using “require”. Get the path of the directory using path.join () method. Pass the directory path and callback function in fs.readdir (path, callbackFunction) Method.

How do I read a file in Node JS?

The simplest way to read a file in Node.js is to use the fs.readFile () method, passing it the file path, encoding and a callback function that will be called with the file data (and the error): Alternatively, you can use the synchronous version fs.readFileSync ():

How to get all files in the directory using NodeJS FS?

We will be using Node.js fs core module to get all files in the directory, we can use following fs methods. Loading... fs.readdir (path, callbackFunction) – This method will read all files in the directory.You need to pass directory path as the first argument and in the second argument, you can any callback function.

How do I resolve a Node JS file to a directory?

In this case Node.js will simply append /joe.txt to the current working directory. If you specify a second parameter folder, resolve will use the first as a base for the second: If the first parameter starts with a slash, that means it's an absolute path:


3 Answers

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; });
like image 83
cliffs of insanity Avatar answered Oct 04 '22 11:10

cliffs of insanity


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);
  }
})();
like image 29
Krzysztof Rosiński Avatar answered Oct 04 '22 11:10

Krzysztof Rosiński


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)
  );
}
like image 33
Mila Nautikus Avatar answered Oct 04 '22 12:10

Mila Nautikus