diff --git a/lib/file.js b/lib/file.js index ff24c27a..a8baf0e9 100644 --- a/lib/file.js +++ b/lib/file.js @@ -19,13 +19,30 @@ Gun.on('opt').event(function(gun, opts) { }); all.keys = all.keys || {}; all.nodes = all.nodes || {}; + + // adapted from https://github.com/toolness/jsondown/blob/master/jsondown.js + var isWriting = false, queuedWrites = []; + function writeFile(cb,info) { + if (isWriting) return queuedWrites.push(cb); + isWriting = true; + fs.writeFile(opts.file, Gun.text.ify(all), function(err) { + isWriting = false; + cb(err); + if (queuedWrites.length) + writeFile( function(err) { + queuedWrites.forEach(function(cb) { cb(err); }) + }); + queuedWrites=[]; + }); + } + gun.opt({hooks: { get: function get(key, cb, o){ var graph, soul; if(soul = Gun.is.soul(key)){ if(all.nodes[soul]){ (graph = {})[soul] = all.nodes[soul]; - cb(null, graph); + cb(null, graph); (graph = {})[soul] = Gun.union.pseudo(soul); cb(null, graph); // end. } @@ -37,14 +54,14 @@ Gun.on('opt').event(function(gun, opts) { return soul? cb(null, {}) : cb(null, null); }, put: function(graph, cb, o){ - all.nodes = gun.__.graph; - fs.writeFile(opts.file, Gun.text.ify(all), cb); + for (key in gun.__.graph) all.nodes[key]=gun.__.graph[key]; + writeFile(cb); }, key: function(key, soul, cb, o){ var meta = {}; meta[Gun._.soul] = soul = Gun.is.soul(soul) || soul; ((all.keys = all.keys || {})[key] = all.keys[key] || {})[soul] = meta; - fs.writeFile(opts.file, Gun.text.ify(all), cb); + writeFile(cb); }, all: function(list, opt, cb) { opt = opt || {}; @@ -85,4 +102,4 @@ Gun.on('opt').event(function(gun, opts) { cb = cb || function() {}; cb(null, r); } -}); \ No newline at end of file +});