safe-replace
A micro-module for safely replacing a file.
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:
touch keep.txt.RANDOM.tmp
rm -f keep.txt.bak
mv keep.txt keep.txt.bak
mv keep.txt.RANDOM.tmp keep.txt
If keep.txt
became corrupt and I wanted to use the backup,
I would do this:
rsync keep.txt.bak keep.txt
In Node
I ported that proccess to node.
sfs.writeFileAsync
sfs.stageAsync
sfs.commitAsync
sfs.revertAsync
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);
});
});
safeReplace.stageAsync('keep.txt', data, 'ascii').then(function (tmpname) {
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
});
});
safeReplace.commitAsync('keep.txt.x7t7sq926.tmp', 'keep.txt').then(function () {
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
});
});
safeReplace.revertAsync('keep.txt').then(function () {
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
});
});