This is intended to be generally safe even when a function that writes a file
is accidentally called twice (as may happen with node cluster).
Commandline Reference
If I want to safely replace a file with a new version, I would do so like this:
# create the new versiontouch keep.txt.RANDOM.tmp# remove the previous backuprm -f keep.txt.bak# move the current version to the backupmv keep.txt keep.txt.bak# move the new version to the currentmv keep.txt.RANDOM.tmp keep.txt
If keep.txt became corrupt and I wanted to use the backup,
I would do this:
# copy the backup to the new versionrsync keep.txt.bak keep.txt
// default behavior is to concat (filename + '.' + rnd() + '.tmp')var safeReplace = require('safe-replace').create({ tmp: 'tmp', bak: 'bak' });var data = new Buffer('A priceless document');safeReplace.writeFileAsync('keep.txt', data, 'ascii').then(function () { fs.readdir('.', function (nodes) { console.log('file system nodes', nodes); // keep.txt // keep.txt.bak });});// let's say I want to write a tmp file and not commit it... weirdsafeReplace.stageAsync(
'keep.txt'
, data,
'ascii'
).
then
(
function
(tmpname) {
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
// keep.txt.ac71teh8mja.tmp
});
});
// let's say I wrote keep.txt.x7t7sq926.tmp with my own mechanism