json-file-enc
Version:
encrypted json for config files
124 lines (99 loc) • 2.49 kB
JavaScript
// Generated by IcedCoffeeScript 1.7.1-b
(function() {
var Data, ec, fs, log, _, _dec, _enc, _reads,
__slice = [].slice;
log = function() {
var x;
x = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return console.log.apply(console, x);
};
_ = require('lodash');
fs = require('fs');
ec = require('easycrypto');
_reads = function(file) {
var d;
if (d = fs.readFileSync(file)) {
return d.toString();
}
};
_enc = function(x, salt, debug) {
var eci;
eci = ec.getInstance();
if (debug) {
return JSON.stringify(x);
}
return eci.encrypt(JSON.stringify(x), salt || 'ca1e51b2d70f61d46288ae437e3d1096');
};
_dec = function(x, salt, debug) {
var eci;
eci = ec.getInstance();
if (debug) {
return JSON.parse(x);
}
return JSON.parse(eci.decrypt(x, salt || 'ca1e51b2d70f61d46288ae437e3d1096'));
};
module.exports = Data = (function() {
Data.prototype.debug_mode = false;
function Data(file, key) {
this.file = file;
this.key = key;
if (!this.key) {
this.key = 'ca1e51b2d70f61d46288ae437e3d1096';
}
}
Data.prototype.debug = function(bool) {
if (bool != null) {
return this.debug_mode = bool;
} else {
return this.debug_mode = true;
}
};
Data.prototype.read = function(def) {
var str;
if (!fs.existsSync(this.file)) {
this.write(def || {});
}
str = _reads(this.file);
return _dec(str, this.key, this.debug_mode);
};
Data.prototype.write = function(obj) {
var str;
str = _enc(obj, this.obj, this.debug_mode);
fs.writeFileSync(this.file, str);
return true;
};
return Data;
})();
/*
if process.env.TAKY_DEV
log /test/
db = new Data './test.dat'
log /reading when noexists/
json = db.read()
log json
log /write/
db.write {
name: 'John Smith'
age: 30
ctime: new Date().getTime()
}
log /reading again/
log db.read()
log /writing again/
json = db.read()
json.name = 'Dave Smith'
db.write json
log /reading last/
log db.read()
process.exit 0
/test/
/reading when noexists/
{}
/write/
/reading again/
{ name: 'John Smith', age: 30, ctime: 1457638376684 }
/writing again/
/reading last/
{ name: 'Dave Smith', age: 30, ctime: 1457638376684 }
*/
}).call(this);