dimanche 5 décembre 2021

How to copy a file and rename it with a random number with js

I have a many files and I need to rename them with shuffle numbers.

Here is an example with 50 files (1 to 50) I found this code and I'am able to get the files renamed and put in a new folders ...

BUT some are not copied since their is some numbers that are generated twice. And if I run the script again and again, I get all my new 50 files but there is some that are duplicated.

const fs = require('fs');

for (let i = 1; i <= 50; i++) {

  function getRandomNumber(min, max) {
    
    let totalEle = max - min + 1;
    let result = Math.floor(Math.random() * totalEle) + min;
    return result;
  }
  function createArrayOfNumber(start, end) {
    let myArray = [];
    for (let i = start; i <= end; i++) {
      myArray.push(i);
    }
    return myArray;
  }
  let numbersArray = createArrayOfNumber(1, 50);

    let randomIndex = getRandomNumber(0, numbersArray.length - 1);
    let randomNumber = numbersArray[randomIndex];
    numbersArray.splice(randomIndex, 1);

    fs.copyFile(`old/${i}.json`, `new/${randomNumber}.json`, (err) => {});
}

It's my first steps in js, I try to figure it out and I'm not... What can I do ?




Aucun commentaire:

Enregistrer un commentaire