javascript - PhantomJS copy file with overwrite -
reading document:
copy(source, destination)
currently, way cope check fs.exist('myfile')
, manual delete prior copy:
var fs = require('fs'); var filename = 'myfile-backup.txt'; if (fs.exists(filename)) { fs.remove(filename); } fs.copy('myfile.txt', filename); phantom.exit();
i don't know if there better way overwrite file. checking existing file may have potential problem when can't remove file. need more error handling approach. seems common task, know solution people come with.
i have written small extension fs
module. if try overwrite file fs.copy
throw exception can catch error handling removing existing file.
i added optional maxtrials
argument if there problem file created every time in between copy
trial , remove
.
var fs = require('fs'); fs.overwrite = function(source, destination, maxtrials){ var overwritten = false; var trials = 0; maxtrials = parseint(maxtrials) maxtrials = !!maxtrials ? maxtrials : null; while(!overwritten) { if (maxtrials && trials > maxtrials) { return -1; } try { this.copy(source, destination); overwritten = true; } catch(e) { if (fs.exists(destination)) { fs.remove(destination); } else { return -2; } } trials++; } return trials; };
Comments
Post a Comment