Find last numbered file in directory?

If you have a directory with files numbered 001.jpg, 002.bmp, 003.jpg… 057.png, 058.jpg, etc., how could you traverse through them and be sure when you get to the highest numbered file? Thanks

Hi,

Assuming you mean using Node and not from the browser (which doesn’t have access to the file system in this way), I would use the fs module to read the directory contents and then sort the files by their numerical part.

Something like this:

const fs = require('fs');

const directoryPath = 'path/to/your/directory';

fs.readdir(directoryPath, (err, files) => {
  if (err) {
    console.error('Error reading the directory', err);
    return;
  }

  const sortedFiles = files
    .map((filename) => ({
      name: filename,
      number: Number(filename.match(/^\d+/)),
    }))
    .sort((a, b) => a.number - b.number)
    .map((file) => file.name);

  sortedFiles.forEach((file) => {
    console.log(file);
  });

  const highestNumberedFile = sortedFiles[sortedFiles.length - 1];
  console.log('Highest numbered file:', highestNumberedFile);
});

LMK if that works for you. I’m happy to explain anything that is unclear.

3 Likes

If you just need the highest number then there is no need to sort, just read the filenames and maintain the highest obtained so far. At the end you will have the highest of all of them.