Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!