NodeJS – path和请求模块| 如何重命名多个副本?

我目前使用的请求,文件系统和path基本上下载100多个URL的图像,并将其存储到本地目录。 我正在使用path来重命名本地目录中存在的任何文件。

我的代码看起来像这样

var download = function (url, dest, cb) { var file = fs.createWriteStream(dest, {flags: 'wx'}); var sendReq = request.get(url); //There's a bunch more code here but I removed it for the sake of relevance file.on('error', function (err) { // Handle errors if (err.code === "EEXIST") { //if image already exist, create new images with same name but numbers let newFileNames = path.parse(dest); for (let p = 1; p <= 5; p+=1) { newFileNames.name += '(' + (p) + ')'; newFileNames.base = newFileNames.name + newFileNames.ext; return download(url, path.format(newFileNames), cb); } } return cb(err.message); }); }; 

我每30秒通过for循环调用下载variables(仅用于testing),如果我使用的是“wx”标志,它将不会覆盖下载的任何现有文件。

我想要达到的是这样的文件

 First download: imageA | imageB | imageC | imageD | Second download: imageA(1) | imageB(1) | imageC(1) | imageD(1) | Third download: imageA(2) | imageB(2) | imageC(2) | imageD(2) | Fourth download: imageA(3) | imageB(3) | imageC(3) | imageD(3) | Fifth download: imageA(4) | imageB(4) | imageC(4) | imageD(4) | 

但是发生的事情是我的文件看起来像这样

 First download: imageA | imageB | imageC | imageD | Second download: imageA(1) | imageB(1) | imageC(1) | imageD(1) | Third download: imageA(1)(1) | imageB(1)(1) | imageC(1)(1) | imageD(1)(1) | Fourth download: imageA(1)(1)(1) | imageB(1)(1)(1) | imageC(1)(1)(1) | imageD(1)(1)(1) | Fifth download: imageA(1)(1)(1)(1) | imageB(1)(1)(1)(1) | imageC(1)(1)(1)(1) | imageD(1)(1)(1)(1) | 

我相当肯定这与我的for循环中的返回有关,因为如果我移动for循环之外,我所请求的文件看起来像这样

 First download: imageA | imageB | imageC | imageD | Second download: imageA(1)(2)(3)(4)(5) | imageB(1)(2)(3)(4)(5) | imageC(1)(2)(3)(4)(5) | imageD(1)(2)(3)(4)(5) | 

这不是我想要的。 另外请注意,我只想下载同一图像的5个副本(图像通过url更新,这就是为什么我想保留多个副本,图像上有时间戳)。 对不起,很长的职位。

编辑1

那么我现在得到它的工作,但我不会认为这种方法有效,卢尔

  file.on('error', function (err) { // Handle errors if (err.code === "EEXIST") { //if image already exist, create new images with same name but numbers dest = dest.slice(0, dest.length -4); var newFileNames = path.parse(dest); console.log(dest); if (dest.endsWith('(1)')) { dest = dest.slice(0, -3); newFileNames = path.parse(dest); newFileNames.name += '(2).jpg'; } else { newFileNames.name += '(1).jpg'; } newFileNames.base = newFileNames.name + newFileNames.ext; } else { fs.unlink(dest, function () { // Delete the file async. ) file.close(cb); }); } return cb(err.message); }); 

它检查文件名是否以(1)结尾(不包括文件扩展名),如果是,则删除(1)并将其replace为(2)。 否则,如果它不包含(1),则将(1)添加到文件名的末尾。

它的工作方式我打算,但如果有一个更有效的方法,你的意见将大大appreicated。 我还是新来的,想尽可能地学习。

编辑2没关系,我已经解决了这个问题。