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

221
Visualizações
Get file type using fs/node.js

I have a folder with few files and I need to get type/extension of the file matching with the number I generate in my num variable, so is there any way I can do it?

My current code is:

fs.readdir(dir, (err, files) => {
  const num = (Math.floor(Math.random() * files.length) + 1).toString();
  // here I need to get file type/extension
}

files variable return this: ['1.jpg', '2.png', '3.gif']

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

0

To find a file in a list of files regardless of the extension, use path.basename and path.extname on the files in the list to chop the extensions. For a single search, use files.find().

const filename = files.find(x => path.basename(x, path.extname(x)) === num.toString())

However, for random selection purposes, it may be better to simply take a random entry from files. The reason is, if the files are all sequentially numbered (from 1) it's the same thing, but if they aren't all sequentially numbered (from 1) the above can break.

const filename = files[num] // and take away + 1 from num
about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of matching the whole file name, You can just generate a random number in ArrayList and get that file.

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

fs.readdir(__dirname, (err, files) => {
  const randomNum = Math.floor(Math.random() * files.length);
  // get the random file
  let randomFileName = files[randomNum];
  console.log(randomFileName);

  /// Get unique exts
  const exts = [...new Set(files.map((name) => path.extname(name)))];
  console.log(exts);
  const randomExt = Math.floor(Math.random() * exts.length);
  
  // Get file with random ext
  randomFileName = files.find((x) => path.extname(x) === exts[randomExt]);
  console.log(randomFileName);
});
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