Question about url collectors
Unanswered
Transvaal lion posted this in #help-forum
Transvaal lionOP
I am building a file hosting app. On top of other features i want to add the code share way. I would like for it to be /code but as the code is made of only lowercase chars and of min 4 char there is a extra small chance that the code ends up upload uploads share urls that already exists. How would i detect if that code goes to an already existing pag?
3 Replies
Transvaal lionOP
async function getRandomCode() {
const publicDir = path.join(process.env.FILESSTORAGEPATH!, "public");
function randomCode(length: number) {
const letters = "abcdefghijklmnopqrstuvwxyz";
return Array.from({ length }, () =>
letters[Math.floor(Math.random() * letters.length)]
).join("");
}
let codeLength = 4;
let code = "";
let tries = 0;
const maxTries = 5;
while (true) {
code = randomCode(codeLength);
const filePath = path.join(publicDir, `${code}.json`);
try {
await fs.access(filePath);
tries++;
if (tries >= maxTries) {
codeLength++;
tries = 0;
}
} catch {
break;
}
}
return code;
}The function i use to generate the random code
Transvaal lionOP
bump