First, prefix each file with a number, incrementing by 1 each time and starting at 0 e.g
0file.txt
1file.txt
2file.txt
... etc
Then when you call the get random file function read each file in turn, and generate a random number from 0
to number of files you have - 1
and output the filename.
const fs = require('fs') //require fs to open files etc
//read files from the directory - I chose a directory called `dir001`
fs.readdir("./dir001", (err, files) => {
if (err) {
console.log(err);
}
let dirFiles = files.filter((f) => f.split(".").pop() === "txt"); // if the files end with txt - change for your needs
if (dirFiles.length === 0) {
console.log("No dir files found"); //if no files found return
return;
}
let randInt = Math.floor(Math.random() * <number of files in the dir>); // generate random number from 0 to number of files in the dir
dirFiles.forEach((f) => {
if (!f.startsWith(randInt)) return; // if the file doesnt start with randInt(), return
message.channel.send(`random file: ${f}`); // output the randomized file
});
});
This should work, please let me know if you get errors, after making sure you changed everything to your individual needs.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…