-1

I am using copy method of fs-extra to copy files from a source to destination. My use case is to create a copy of the file with a name like if a file of the same name exists in the destination. The copy method of fs-extra module overwrites the destination file.

Ravi Kukreja
  • 587
  • 1
  • 6
  • 17

1 Answers1

0

You could try something like this:

const fs = require('fs-extra');

async function copy(src, dest) {
  try {
    await fs.copy(src, dest, { overwrite: false, errorOnExist: true });
    return true;
  } catch (error) {
    if (error.message.includes('already exists')) {
      return false;
    }
    throw error;
  }
}

async function copyWithoutOverwrite(src, dest, maxAttempts) {    
  try {
    if (!await copy(src, dest)); {
      for (let i = 1; i <= maxAttempts; i++) {
        if (await copy(src, `${dest}_copy${i}`)) {
          return;
        }
      }
    }
  } catch (error) {
    console.error(error);
  }
}

const src = '/tmp/testfile';
const dest = '/tmp/mynewfile';
const maxAttempts = 10;

copyWithoutOverwrite(src, dest, maxAttempts);
nijm
  • 1,856
  • 9
  • 26