Home > Net >  How could I duplicate/copy file in an automatized way with JavaScript?
How could I duplicate/copy file in an automatized way with JavaScript?

Time:05-22

I have an gif file that is stored in a directory call assets on my computer. I would like to create X amount of duplicates and they should be stored in the same directory and each of them should have a different file name.

Example:

I in the assets directory is the gif file call 0.gif I would like to duplicate this gif file 10 times and The duplicates should be called 1.gif, 2.gif, 3.R and so on.

CodePudding user response:

const fs = require("fs")
const filename = "index.js".split(".") //filename like 0.gif to gif
const times = 10 // number of times to duplicate

for(var int = 1; int < times; int  ){
    const newFilename = `${(parseInt(filename[0])   init)}.${filename[1]}`  //new filename like 0.gif to 1.gif
    copyFileSync(filename, newfilename)
}

use the write file and read file from the fs module and a simple for loop

CodePudding user response:

The simplest option is to use fs and using copyFile function available

const fs = require("fs");
const path = require("path");

let copyMultiple = (src, count) => {
 let initCount = 0;

 while (initCount < count) {
   initCount  ;// you can put this at bottom too acc to your needs
   const newFileName = `${initCount}_${initCount}${path.extname(src)}`;
   console.log(newFileName, "is new file name");
   fs.copyFile(src, newFileName, (error) => {
     // if errors comes
     if (error) {
       console.log(error);
     }
   });
 }
};
copyMultiple("1.gif", 3);

Another elegant way of doing this is

const util = require("util");
const fs = require("fs");
const path = require("path");
const copyFilePromise = util.promisify(fs.copyFile);

function copyFiles(srcFile, destDir, destFileNames) {
  return Promise.all(
    destFileNames.map((file) => {
      return copyFilePromise(srcFile, path.join(destDir, file));
    })
  );
}

const myDestinationFileNames = ["second.gif", "third.gif"];
const sourceFileName = "1.gif";

copyFiles(sourceFileName, "", myDestinationFileNames)
  .then(() => {
    console.log("Copying is Done");
  })
  .catch((err) => {
    console.log("Got and Error", error);
  });

Using this will also give upperhand of knowing when it is done.

You can read docs here

CodePudding user response:

not sure which framework you're on but fs.copyFile() is the standard way for node.js https://nodejs.org/api/fs.html#fscopyfilesrc-dest-mode-callback

  • Related