Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename.

For example:

If there is a GIF file named "0.gif" in the assets directory, I would like to make 10 copies of this file and name them "1.gif," "2.gif," "3.gif," and so on.

Answer №1

To simplify the process, one can utilize the fs module along with the copyFile function.

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

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

 while (initCount < count) {
   initCount++;
   const newFileName = `${initCount}_${initCount}${path.extname(src)}`;
   console.log(newFileName, "is new file name");
   fs.copyFile(src, newFileName, (error) => {
     if (error) {
       console.log(error);
     }
   });
 }
};
copyMultiple("1.gif", 3);

Another more sophisticated approach is presented below:

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);
  });

This method also provides the advantage of tracking the completion status.

For further information, refer to the documentation here

Answer №2

const fs = require("fs")
const fileName = "index.js".split(".") //file name split into parts like 0.gif
const duplications = 10 // number of times to create duplicates

for(var count = 1; count < duplications; count++){
    const newFileName = `${(parseInt(fileName[0]) + count)}.${fileName[1]}`  //new file name like 0.gif becomes 1.gif
    fs.copyFileSync(fileName, newFileName)
}

Utilize the write and read functions from the fs module along with a basic for loop

Answer №3

If you're unsure about the framework you're using, fs.copyFile() is a common method for node.js development. You can find more information about it at this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The system is unable to access the "db" property due to its null value

Currently, I am diving into the world of Node.js. However, as I progress, I have encountered a puzzling error My code is pretty straightforward: let express = require('express') let mongodb = require('mongodb') let server = express() ...

Enhancing my code by implementing various conditions in React

Looking for ways to enhance my code quality (Very Important, Important, Medium, Low, Good, Excellent,...) : { Header: "Opinion", accessor: (row) => row.opinion, Cell: props => <span> {props.value == ...

After removing the timezone from the timestamp log, why is it now showing as one day behind?

Within my programming, I store a timestamp in the variable 'var timeStamp = finalData.obj.followers[0].timestp;', which currently outputs '2020-04-15T00:00:00.000Z.' To extract only the date and remove the time zone information, I util ...

Trouble with Google Bar Chart's Background Color not Updating

I'm having issues with the background color in my google Material Charts static api library. Despite entering a specific color code, the change is not being reflected when the page loads. These are the options I have set: var options = { b ...

Revamp the website's design

I am looking to revamp the color theme of my website with just a click of a button. Can someone provide me with a link to a reference website where I can get some inspiration? ...

Verify if a certain value exists in an array while using ng-if inside ng-repeat

Currently, I have a loop using ng-repeat that goes through a list of wines obtained from an API. Alongside this, there is an array variable containing all the IDs of wines that have been marked as favorites and retrieved from the database. My goal is to sh ...

Creating a textured path using Threejs

Having trouble drawing a path in my 3D world, as the line class is not helpful. Can anyone offer assistance? See this image I've updated my question I want to draw a path and fill it with texture. var SUBDIVISIONS = 20; geometry = new THREE.Geo ...

json request not functioning properly in Internet Explorer and experiencing difficulties with caching

Unfortunately, the code snippet provided below is compatible only with Firefox and not Internet Explorer. The JSON file breaks when it encounters the text "Meanscoil na mBraithre Criostaí": "2028425":[19, "Awaiting Correction", "", "Meanscoil na mBra ...

Implement a feature in JS/HTML where clicking on a button shifts a specific section of a row from one table to another while simultaneously deleting the remaining

I am facing an issue with two tables - addFriends and existingFriends. The addFriends table contains a button in the fourth column, which, upon clicking, should delete the corresponding row from that table and add it to the existingFriends table. Currentl ...

Is there a way to bring to life the addClass() and removeClass() jQuery functions through animation?

I am currently developing a website and I want to be able to toggle the visibility of sections by using the ".hidden" bootstrap class within click events. Here is the basic code snippet: $('selector').click(function(){ $('*part-to-hi ...

Cookie Multitree: An Innovative JsTree Solution

Hello everyone, I am currently using jstree and have come across a couple of issues with having multiple trees on the same page. Here are my two problems: 1) I am looking to implement cookies to keep track of which nodes are open in each tree. I attempted ...

Having difficulty generating dynamic rows and tree dropdowns in AngularJS

Struggling to implement dynamic row functionality with Angular JS. The rows are working well, but I also need to incorporate a tree dropdown within each row. Unfortunately, clicking the "add row" button populates the same data in all rows. I have shared m ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Exploring all Azure assets with NodeJS

I've been working on using the Azure SDK for JavaScript to list all resources within an Azure subscription. My current approach involves authenticating with the @azure/ms-rest-nodeauth package and then utilizing the ResourceManagementClient from the @ ...

How can I incorporate eventData when using .bind() for the "keydown" event type?

I want to achieve something like this: var keydownHandler = function (ev) { alert(ev.data.test); return false; } $(document).bind('keydown', {test: 'foo'}, keydownHandler); However, the .bind method doesn't seem to be wor ...

Utilize Jquery to extract HTML content from an array of links and implement regular expressions

Currently, I am embarking on the journey of developing a Google Chrome extension despite my limited experience in this field. My aim is to create a tool that can identify individuals who have left reviews on Amazon products. Specifically, I am looking to l ...

Disable body scrolling on mobile devices in native browsers

When using the native browser on Samsung Galaxy S5 / S6, the following CSS code: body { overflow: hidden; } does not successfully prevent the body from scrolling. Is there a way to work around this issue? Edit: As mentioned below, one workaround is t ...

The npm installation process stalls while loading all dependencies into the ideal tree during the loadIdealTree:loadAllDepsIntoIdealTree stage

Having an issue with my Node.js application. Whenever I try to run npm install, it gets stuck on this message: loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree Adding --verbose to the command gives me a bit more information: npm info i ...

Opening the media library in Wordpress through the Angular JS function triggered by an ng-click event

I have been working on a plugin where I need to select an image from the media library. However, despite having implemented the code correctly to call the media library window, I encounter an issue. When I click the button to select an image, nothing happe ...

Troubleshooting: Why isn't setMetadata working in NestJS from authGuards

When I call my decorators, I want to set metadata for logging purposes. Within my controller, the following decorators are used: @Post("somePath") @Permission("somePermission") @UseGuards(JwtAuthGuard) @HttpCode(200) @Grafana( ...