简体   繁体   中英

How can i catch and handle Error: EEXIST: file already exists, copyfile "somepath" "anotherpath" in nodejs

I want to change the name of file when i get duplicate files while performing copy operation in nodejs using fs module (right now the process exits with error, i want to execute file name change logic on error)

function copyFile(filePath,fileName){
fs.copyFileSync(filePath, 
    path.join(destination,fileName),fs.constants.COPYFILE_EXCL, (err) => {
    if (err) {
        fileName=  "0"+fileName; //changing the filename
        copyFile(filePath,fileName)
    }
    console.log(fileName+" copied");
  })
}

You simply need to check if error.code === 'EEXIST' .

Few notes:

  • copyFileSync does not accept callback - it's a synchronous function
  • You're using path.join incorrectly. This utility is used mainly to provide cross-platform paths (Unix - / , Windows - \\ ). If you're concatenating it yourself with / there is no point to use path.join it will not work on non-unix systems anyway.
  • There is a typo filename -> fileName
  • You need two fileName... arguments for copyFile function ( source and destination ), because source file with prepended 0 -s not exists by the moment you're calling the function.
const fs = require('fs');
const path = require('path');

const destination = '/tmp/';

function copyFile(filePath, fileNameFrom, fileNameTo=fileNameFrom) {
  const from = path.join(filePath, fileNameFrom);
  const to = path.join(destination, fileNameTo);

  try {
    fs.copyFileSync(from, to, fs.constants.COPYFILE_EXCL);
    console.log(`${from} copied into ${to}`);
  } catch (error) {
    console.error(error);
    if (error.code === 'EEXIST') {
      copyFile(filePath, fileNameFrom, '0' + fileNameTo);
    }   
  }
}


copyFile('/tmp/test', 'a.txt');

Note : do not forget to change destination variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM