-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
29 lines (26 loc) · 840 Bytes
/
index.js
File metadata and controls
29 lines (26 loc) · 840 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const path = require('path')
const fs = require('fs')
module.exports = function (dir, callback) {
fs.readdir(dir, (err, files) => {
if (err) return callback(err)
function checkRandom () {
if (!files.length) {
// callback with an empty string to indicate there are no files
return callback(null, undefined)
}
const randomIndex = Math.floor(Math.random() * files.length)
const file = files[randomIndex]
fs.stat(path.join(dir, file), (err, stats) => {
if (err) return callback(err)
if (stats.isFile()) {
return callback(null, file)
}
// remove this file from the array because for some reason it's not a file
files.splice(randomIndex, 1)
// try another random one
checkRandom()
})
}
checkRandom()
})
}