How to return Random filename from a folder?

Hello guys,

I am working on a meteor app for people to practice their English.
If you’re curious, you can see the gameplay at

I need a filename from a folder, is it better to push all the filenames to a db Collection a pull the random filename from there?

I get the random doc from a collection like this:

let query = [
  { $match: { status: 'published' } },
  { $sample: { size: 1 } }
let result = Questions.aggregate(query);

How can I get a random filename from a folder?

Here another video from my meteor app (feedback would be great)


You can get the filename from the folder by doing something like this.

function isFile(source) {
  return lstatSync(source).isFile();

function getFiles(source) {
  return readdirSync(source).map((name) => join(source, name)).filter(isFile);

const files = getFiles(DIR);

const file = files[RANDOM_NUMBER];

But I will suggest to do it with the DB, inserting a doc on each upload so that later you can get it. That way you could also do it with S3 or any other storage saving the URL.

Hope this helps.

1 Like