有没有一种简单的方法可以让node.js在保存文件时增加文件名(即追加一个数字),以避免覆盖之前的文件?
以下是我的尝试:
以下是我的尝试:
// can i make this a one-liner?:)
async function incrementIfExists(dirPath, fileName, data, increment=1) {
const fs = require('fs'),
path = require('path'),
errorFunc = (err) => console.error(err);
// Get the last file saved with same fileName (i.e., the one that has the greatest increment number), if there is one
let lastFile = await fs.promises.readdir(dirPath)
.then(files => {
let result = '';
for (const name of files) {
if (!name.startsWith(fileName)) continue;
if ((name.length < result.length) || (name.length === result.length && name < result)) continue;
result = name;
}
return result;
})
.catch(errorFunc);
if (lastFile) {
const lastIncrementNr = Number(lastFile.slice((fileName + '_').length));
if (increment <= lastIncrementNr) increment = lastIncrementNr + 1;
}
fileName = path.join(dirPath, fileName);
while (true) {
let breakLoop = await fs.promises.writeFile(lastFile ? fileName + '_' + increment : fileName, data, {encoding: 'utf8', flag: 'wx'})
.then(fd => true)
.catch(err => {
if (err.code === 'EEXIST') {console.log(err);
return false;
}
throw err;
});
if (breakLoop) break;
increment++;
}
}
incrementIfExists('.', fileName, data);
async
函数有什么好处呢? - flenconst writeFileAsync
。但你比我更了解你的代码,所以我就不多说了。现在我想我明白你的意思了,始终使用async
可以让它更容易被发现,特别是对于自动化工作来说。 - flen