Is there a simple way to make node.js increment the filename of a file (i.e., append a number, so that it doesn't overwrite previous files) when saving it?
Below is my attempt:
// 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);
Related:
How to not overwrite file in node.js
Creating a file only if it doesn't exist in Node.js