Skip to content

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']


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