First, you check if the file exists. If it does, modify a name and save it again. Something like that.
(function() {
try {
var contents = 'Lorem ipsum';
var pathToFile = '~/Desktop/test.js';
var file = new File(pathToFile);
if (!file.exists) {
writeFile(file, contents);
} else {
var fileName = getFileName(file);
var date = new Date();
var extensions = getExtension(file);
file = new File(file.parent.fsName + '/' + fileName + ' ' + date.toString() + '.' + extensions);
writeFile(file, contents);
}
} catch (e) {
alert(e.toString() + '\nScript File: ' + File.decode(e.fileName).replace(/^.*[\|\/]/, '') +
'\nFunction: ' + arguments.callee.name +
'\nError on Line: ' + e.line.toString());
}
function getFileName(file) {
return file.name.split('.').slice(0, -1).join('.');
}
function getExtension(file) {
return file.name.split('.').pop();
}
function writeFile(file, contents, encoding, openMode) {
var success;
file = (file instanceof File) ? file : new File(file);
encoding = encoding || 'UTF-8';
openMode = openMode || 'w'; // 'a', 'e', 'r', 'w';
file.encoding = encoding;
file.open(openMode);
success = file.write(contents);
file.close();
if (!success) {
throw new Error('Unable to write file ' + file.fsName);
}
return file;
}
})();
... View more