How to create a list of random file names, including extension, dates, and file size in JavaScript

1 Answer

0 votes
// Required libraries
const crypto = require("crypto");

// Function to generate a random string of given length
function generateRandomString(length) {
  const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  const bytes = crypto.randomBytes(length);
  
  return Array.from(bytes, b => charset[b % charset.length]).join("");
}

// Function to generate a random date
function generateRandomDate() {
  const year = crypto.randomInt(2000, 2021);  // 2000–2020
  const month = crypto.randomInt(1, 13);      // 1–12
  const day = crypto.randomInt(1, 29);        // 1–28

  return `${year.toString().padStart(4, "0")}-${month
    .toString()
    .padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
}

// Function to generate a random file size
function generateRandomFileSize() {
  return crypto.randomInt(1, 100001); // 1–100000 bytes
}

const extensions = [".txt", ".jpg", ".png", ".cpp", ".pdf"];
const numberOfFiles = 10;
const fileLength = 9;

for (let i = 0; i < numberOfFiles; i++) {
  const fileName = generateRandomString(fileLength);
  const extension = extensions[crypto.randomInt(extensions.length)];
  const date = generateRandomDate();
  const fileSize = generateRandomFileSize();

  console.log(`${fileName}${extension} ${date} ${fileSize} bytes`);
}



/*
run:

NuRRD2KUX.txt 2017-02-10 69297 bytes
yArSM0sYZ.png 2017-12-12 4108 bytes
hzMmH8TqE.txt 2019-04-22 24290 bytes
RjeKjoeqF.jpg 2016-09-20 7670 bytes
h92UxcbgS.png 2007-12-03 92993 bytes
OOH7tteo6.pdf 2005-04-19 26052 bytes
UWaBRLEyb.jpg 2003-03-07 30305 bytes
8pHhgqNfI.jpg 2006-05-12 99940 bytes
cvj6Zw5U2.pdf 2013-07-03 38290 bytes
1NCguOPIa.pdf 2020-07-06 93160 bytes

*/

 



answered 6 hours ago by avibootz

Related questions

...