Find the Newest File in Directory Using NodeJS

08-03-2020

There are times you might need to find the latest file in a given directory. This method is not the most efficient and will have some performance costs (👀 synchronous processing 👀). Almost every time I reach for something like this it is for a utility function, like ‘find the latest database schema for testing purposes’. Usually I’m searching through a relatively small group of files during local development.

The Basic Idea

  1. Identify the directory we want to search. This needs to be an absolute path to the directory.
  2. Read all of the contents of the directory
  3. Filter to only return the contents that are a file
  4. Create an absolute path for the file using .map()
  5. Sort the array of files by the modified time (mtime) to get the most recently modified file first
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const fs = require("fs");
const path = require("path");

const getMostRecentFile = (dir) => {
const files = orderReccentFiles(dir);
return files.length ? files[0] : undefined;
};

const orderReccentFiles = (dir) => {
return fs.readdirSync(dir)
.filter((file) => fs.lstatSync(path.join(dir, file)).isFile())
.map((file) => ({ file, mtime: fs.lstatSync(path.join(dir, file)).mtime }))
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
};

console.log(getMostRecentFile('/api/database/schemas/'));

The result will be an object with first file in the sorted array. e.g.

1
{ file: 'db-2020-08-03-12:13.sql', mtime: 2020-08-03T16:13:46.000Z }

This solution sorts the array based on the modified time (mtime) for each file. The created time (ctime) is also an available option, though the results could certainly differ.

Based on a suggested StackOverflow solution here