首页 > 解决方案 > 我如何捕获和处理错误:EEXIST:文件已存在,在nodejs中复制文件“somepath”“anotherpath”

问题描述

当我使用 fs 模块在 nodejs 中执行复制操作时获取重复文件时,我想更改文件名(现在该进程因错误退出,我想在错误时执行文件名更改逻辑)

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

标签: node.js

解决方案


您只需要检查是否error.code === 'EEXIST'.

几点注意事项:

  • copyFileSync不接受回调 - 这是一个同步函数
  • 你使用path.join不正确。该实用程序主要用于提供跨平台路径(Unix - /,Windows - \)。如果您自己将其连接起来,/那么使用path.join它无论如何都不会在非 unix 系统上工作。
  • 有错别字filename->fileName
  • 函数 (和)需要两个fileName...参数,因为在调用函数时,带有前置-s 的源文件不存在。copyFilesourcedestination0
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');

注意:不要忘记更改destination变量


推荐阅读