Home > Software design >  Find the newest folder in a directory with NodeJS
Find the newest folder in a directory with NodeJS

Time:05-20

I need to find a way to get the newest folder created in a directory. Usually there are 3-5 different folders inside of a folder, and I want to find the newest one either by folder name (newest version numbering) or date and time created. Generally the folder name would like like this:

version-0101xxxxxxxxxxxx

(x representing the newest version)

CodePudding user response:

You can get directories with 'fs' using 'readdirSync', then look inside each directory recursively.

This code snippet is extracted from (this answered question):

const fs = require('fs');
const path = require('path');

function flatten(lists) {
  return lists.reduce((a, b) => a.concat(b), []);
}

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath)
    .map(file => path.join(srcpath, file))
    .filter(path => fs.statSync(path).isDirectory());
}

function getDirectoriesRecursive(srcpath) {
  return [srcpath, ...flatten(getDirectories(srcpath).map(getDirectoriesRecursive))];
}

let dirs = getDirectoriesRecursive(__dirname);
console.info(path);

This will get you an array with all directories, then you just need to loop your array with the condition you need.

CodePudding user response:

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);
}
  • Related