I want to make this code to change filename if file exists instead of overwritng it.
var fileName = 'file';
fs.writeFile(fileName + '.txt', 'Random text', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
Something like:
var fileName = 'file',
checkFileName = fileName,
i = 0;
while(fileExists(checkFileName + '.txt')) {
i++;
checkFileName = fileName + '-' + i;
} // file-1, file-2, file-3...
fileName = checkFileName;
fs.writeFile(fileName + '.txt', 'Random text', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
How can I make "fileExists" function, considering that fs.exists()
is now deprecated and fs.statSync()
or fs.accessSync()
throws error if file doesn't exist. Maybe there is a better way to achieve this?