fs-safe-replace.js/README.md

87 lines
2.0 KiB
Markdown
Raw Permalink Normal View History

2015-07-17 23:07:02 +00:00
safe-replace
============
A micro-module for safely replacing a file.
2015-12-15 06:07:54 +00:00
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).
2015-07-17 23:07:02 +00:00
Commandline Reference
---------------------
If I want to safely replace a file with a new version, I would do so like this:
```bash
# create the new version
2015-12-15 06:07:54 +00:00
touch keep.txt.RANDOM.tmp
2015-07-17 23:07:02 +00:00
# remove the previous backup
rm -f keep.txt.bak
# move the current version to the backup
mv keep.txt keep.txt.bak
# move the new version to the current
2015-12-15 06:07:54 +00:00
mv keep.txt.RANDOM.tmp keep.txt
2015-07-17 23:07:02 +00:00
```
If `keep.txt` became corrupt and I wanted to use the backup,
I would do this:
```bash
# copy the backup to the new version
rsync keep.txt.bak keep.txt
```
In Node
-------
I ported that proccess to node.
2015-12-15 07:04:55 +00:00
```
sfs.writeFileAsync
sfs.stageAsync
sfs.commitAsync
sfs.revertAsync
```
2015-07-17 23:07:02 +00:00
```js
2015-12-15 07:04:55 +00:00
// default behavior is to concat (filename + '.' + rnd() + '.tmp')
var safeReplace = require('safe-replace').create({ tmp: 'tmp', bak: 'bak' });
2015-07-17 23:07:02 +00:00
var data = new Buffer('A priceless document');
2015-12-15 07:04:55 +00:00
safeReplace.writeFileAsync('keep.txt', data, 'ascii').then(function () {
2015-07-17 23:07:02 +00:00
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
// keep.txt
// keep.txt.bak
});
});
2015-12-15 07:04:55 +00:00
// let's say I want to write a tmp file and not commit it... weird
safeReplace.stageAsync('keep.txt', data, 'ascii').then(function (tmpname) {
2015-07-17 23:07:02 +00:00
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
2015-12-15 07:04:55 +00:00
// keep.txt.ac71teh8mja.tmp
2015-07-17 23:07:02 +00:00
});
});
2015-12-15 07:04:55 +00:00
// let's say I wrote keep.txt.x7t7sq926.tmp with my own mechanism
safeReplace.commitAsync('keep.txt.x7t7sq926.tmp', 'keep.txt').then(function () {
2015-07-17 23:07:02 +00:00
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
// keep.txt
// keep.txt.bak
});
});
2015-12-15 06:07:54 +00:00
2015-12-15 07:04:55 +00:00
// let's say I want to revert the file from the '.bak'
safeReplace.revertAsync('keep.txt').then(function () {
2015-12-15 06:07:54 +00:00
fs.readdir('.', function (nodes) {
console.log('file system nodes', nodes);
// keep.txt
// keep.txt.bak
});
});
2015-07-17 23:07:02 +00:00
```