UNPKG

json-update

Version:

Allows for very simple JSON file updating in one line

118 lines (102 loc) 2.77 kB
// Generated by ToffeeScript 1.6.3-4 (function() { var cfg, deepExtend, fs, lockfile, opts, pify, und; fs = require('fs-extra'); lockfile = require('lockfile'); und = require('underscore'); deepExtend = require('deep-extend'); pify = require('pify'); opts = { wait: 2000, stale: 30000, retries: 2, retryWait: 100 }; cfg = { deep: false }; exports.config = function(conf) { return cfg = und.extend(cfg, conf); }; function fixempty(cb) { if (cb == null) { return (function() {}); } else { return cb; } }; function doload(filename, unlock, cb) { var data, e, er, err, _this = this; cb = fixempty(cb); lockfile.lock("" + filename + ".lock", opts, function() { er = arguments[0]; if (er != null) { return cb(er); } else { fs.readFile(filename, 'utf8', function() { err = arguments[0], data = arguments[1]; if (unlock) { lockfile.unlock("" + filename + ".lock", function() { _$$_0(); }); } else { _$$_0(); } function _$$_0() { if (err != null) { return cb(new Error("Error reading JSON file " + filename + ": " + (err != null ? err.message : void 0))); } try { return cb(null, JSON.parse(data)); } catch (_error) { e = _error; return cb(new Error("Error parsing JSON in " + filename + ". Data is " + data + ". Error was " + e.message)); } }; }); } }); }; function load(filename, cb) { return doload(filename, true, cb); }; function update(filename, obj, cb) { var err, filedata, _this = this; cb = fixempty(cb); function loaded(data) { var err, _this = this; if (!cfg.deep) { data = und.extend(data, obj); } else { deepExtend(data, obj); } fs.outputJson(filename, data, function() { err = arguments[0]; lockfile.unlock("" + filename + ".lock", function() { if (err != null) { return cb(new Error("Problem saving JSON file: " + (err != null ? err.message : void 0))); } return cb(null, data); }); }); }; fs.exists(filename, function(_$$_3) { _$cb$_2(!_$$_3); }); function _$cb$_2(_$$_1) { if (_$$_1) { return loaded({}, false); } else { doload(filename, false, function() { err = arguments[0], filedata = arguments[1]; return loaded(filedata, false); }); } }; }; exports.load = pify(load); exports.update = pify(update); }).call(this);