Commit 0644061d62c451cf63f1489c1b7e8c5bab16b76b
add loadOrCreate
Dominic Tarr committed on 11/1/2014, 12:27:44 PMParent: 3c86f2b6d1444f5a148454cbe412609ffc372808
Files changed
index.js | changed |
index.js | ||
---|---|---|
@@ -2,8 +2,10 @@ | ||
2 | 2 | var crypto = require('crypto') |
3 | 3 | var ecc = require('eccjs') |
4 | 4 | var k256 = ecc.curves.k256 |
5 | 5 | var Blake2s = require('blake2s') |
6 | +var mkdirp = require('mkdirp') | |
7 | +var path = require('path') | |
6 | 8 | |
7 | 9 | function bsum (value) { |
8 | 10 | return new Blake2s().update(value).digest() |
9 | 11 | } |
@@ -52,17 +54,35 @@ | ||
52 | 54 | } |
53 | 55 | |
54 | 56 | exports.create = function(namefile, cb) { |
55 | 57 | var k = constructKeys() |
56 | - fs.writeFile(namefile, k.keyfile, function(err) { | |
57 | - if (err) return cb(err) | |
58 | - delete k.keyfile | |
59 | - cb(null, k) | |
58 | + mkdirp(path.dirname(namefile), function (err) { | |
59 | + if(err) return cb(err) | |
60 | + fs.writeFile(namefile, k.keyfile, function(err) { | |
61 | + if (err) return cb(err) | |
62 | + delete k.keyfile | |
63 | + cb(null, k) | |
64 | + }) | |
60 | 65 | }) |
61 | 66 | } |
62 | 67 | |
63 | 68 | exports.createSync = function(namefile) { |
64 | 69 | var k = constructKeys() |
70 | + mkdirp.sync(path.dirname(namefile)) | |
65 | 71 | fs.writeFileSync(namefile, k.keyfile) |
66 | 72 | delete k.keyfile |
67 | 73 | return k |
68 | -} | |
74 | +} | |
75 | + | |
76 | +exports.loadOrCreate = function (namefile, cb) { | |
77 | + exports.load(namefile, function (err, keys) { | |
78 | + if(!err) return cb(null, keys) | |
79 | + exports.create(namefile, cb) | |
80 | + }) | |
81 | +} | |
82 | +exports.loadOrCreateSync = function (namefile) { | |
83 | + try { | |
84 | + return exports.loadSync(namefile) | |
85 | + } catch (err) { | |
86 | + return exports.createSync(namefile) | |
87 | + } | |
88 | +} |
Built with git-ssb-web