Skip to content

Instantly share code, notes, and snippets.

@pianosnake
Created July 30, 2018 19:11
Show Gist options
  • Save pianosnake/44ab1174228905fe25b7d3e23b7f48b0 to your computer and use it in GitHub Desktop.
Save pianosnake/44ab1174228905fe25b7d3e23b7f48b0 to your computer and use it in GitHub Desktop.
Get the name of the most recently created file in a given directory using Node.js
const fs = require('fs');
const path = require('path');
function getMostRecentFile(dir) {
const files = fs.readdirSync(dir);
let earliestCreate = 0;
let mostRecentFile = files[0];
files.forEach(file => {
if (fs.statSync(path.join(dir, file)).ctime > earliestCreate) {
mostRecentFile = file;
}
});
return mostRecentFile;
}
//getMostRecentFile('./my-dir');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment