You can use node.js built-in fs module for this. First of all you need to list all the files and folders in the directory that you intend to search.
let dirs = await fs.readdir(dirName, {
withFileTypes: true,
});
You can use fs.promises.readdir for this. Make sure to add the option "withFileTypes" because it gives additional information that you can use to distinguish folders from files.
You can then filter all files like this:
dirs = dirs.filter((file) => file.isDirectory()).map((dirent) => dirent.name);
This gives you a result like ["firstFolder", "secondFolder", etc]
And then you can loop through the above array and find the newest folder by using the fs.promises.stat method
let newestFolder = await fs.stat(path.join(dirName, dirs[0]));
let newestFolderName = dirs[0];
for (let directory of dirs) {
const stats = await fs.stat(path.join(dirName, directory));
if (stats.ctimeMs > newestFolder.ctimeMs) {
newestFolder = stats;
newestFolderName = directory;
}
}
And then you can create the absolute path of that directory using path module:
const absoultePath = path.resolve(path.join(dirName, newestFolderName));
Here is how the function looks using promises:
const fs = require("fs/promises");
const path = require("path");
async function getNewestDirectory(dirName) {
let dirs = await fs.readdir(dirName, {
withFileTypes: true,
});
dirs = dirs.filter((file) => file.isDirectory()).map((dirent) => dirent.name);
let newestFolder = await fs.stat(path.join(dirName, dirs[0]));
let newestFolderName = dirs[0];
for (let directory of dirs) {
const stats = await fs.stat(path.join(dirName, directory));
if (stats.ctimeMs > newestFolder.ctimeMs) {
newestFolder = stats;
newestFolderName = directory;
}
}
console.log("newestFolder", newestFolder);
console.log("newestFolderName", newestFolderName);
return path.resolve(path.join(dirName, newestFolderName));
}
and using synchronous approach(not recommended):
const fs = require("fs");
let dirs = fs.readdirSync(".", {
withFileTypes: true,
});
dirs = dirs.filter((file) => file.isDirectory()).map((dirent) => dirent.name);
let newestFolder = fs.statSync(dirs[0]);
let newestFolderName = dirs[0];
for (let directory of dirs) {
const stats = fs.statSync(directory);
if (stats.ctimeMs > newestFolder.ctimeMs) {
newestFolder = stats;
newestFolderName = directory;
}
console.log("newestFolder", newestFolder);
console.log("newestFolderName", newestFolderName);
}