Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda