git ssb

0+

Dominic / atomic-file



Tree: 4f2a6bbebfabc07c05d662c59303eeeaa47b166b

Files: 4f2a6bbebfabc07c05d662c59303eeeaa47b166b / index.js

1247 bytesRaw
1var fs = require('fs')
2
3function isFunction (f) {
4 return 'function' === typeof f
5}
6
7module.exports = function (filename, suffix, _codec) {
8 var codec = _codec || require('./codec')
9 suffix = suffix || '~'
10 var queue = []
11 var value
12 return {
13 get: function (cb) {
14 if(value) return cb(null, value)
15 else fs.readFile(filename, 'utf8', function (err, _value) {
16 if(err) return cb(err)
17 try {
18 value = codec.decode(_value)
19 } catch (err) {
20 return cb(err)
21 }
22 cb(null, value)
23 })
24 },
25 //only allow one update at a time.
26 set: function put (_value, cb) {
27 if(!isFunction(cb)) throw new Error('cb must be function')
28 if(queue.length) {
29 return queue.push(function retry () {
30 put(_value, cb)
31 })
32 }
33 queue.push(cb)
34
35 function done (err) {
36 var _queue = queue
37 queue = []
38 while(_queue.length) _queue.shift()(err)
39 }
40
41 fs.writeFile(filename+suffix, codec.encode(_value), function (err) {
42 if(err) return done(err)
43 fs.rename(filename+suffix, filename, function (err) {
44 if(err) done(err)
45 else done(null, value = _value)
46 })
47 })
48 }
49 }
50}
51
52
53

Built with git-ssb-web