node.js - 我如何捕获和处理错误: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");
})
}
解决方案
您只需要检查是否error.code === 'EEXIST'
.
几点注意事项:
copyFileSync
不接受回调 - 这是一个同步函数- 你使用
path.join
不正确。该实用程序主要用于提供跨平台路径(Unix -/
,Windows -\
)。如果您自己将其连接起来,/
那么使用path.join
它无论如何都不会在非 unix 系统上工作。 - 有错别字
filename
->fileName
- 函数 (和)需要两个
fileName...
参数,因为在调用函数时,带有前置-s 的源文件不存在。copyFile
source
destination
0
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
变量
推荐阅读
- android - 带有子元素和根的 LinearLayout 是一个滚动视图。它应该被包装到另一个滚动视图吗?
- flutter - Flutter 地理定位器插件 Geolocator().placemarkFromAddress() 和 Geolocator().placemarkFromCoordinates() 不起作用
- javascript - 递归函数在Javascript中运行时如何执行回调函数?
- javascript - 如何显示带有动态变量的 toastr 消息
- r - R:在销售数据中插入缺失观察的行
- sql - 如何加入多个表进行计数?
- node.js - Aws lambda图像上传问题
- c++ - 如何针对 C++ Qt 中的链接器优化我的项目?
- python - anaconda自带的python解释器和官方的python解释器发行版有区别吗?
- python - 如何访问类中函数中的列表?