Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Find the newest folder in a directory with NodeJS

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)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda