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']
CodePudding user response:
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 it's the same thing, but if they aren't all sequentially numbered the above can break.
const filename = files[num] // and take away 1 from num
CodePudding user response:
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);
});