-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathstorage.js
653 lines (591 loc) · 15.9 KB
/
storage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
/*
* The MIT License
*
* Copyright (c) 2016 Juan Cruz Viotti. https://github.com/jviotti
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
/**
* @module storage
*/
const _ = require('lodash');
const async = require('async');
const fs = require('fs');
const rimraf = require('rimraf');
const mkdirp = require('mkdirp');
const path = require('path');
const writeFileAtomic = require('write-file-atomic');
const utils = require('./utils');
const lock = require('./lock');
const readFile = function (fileName, callback, times) {
times = times || 0;
fs.readFile(fileName, function (error, object) {
if (!error) {
return callback(null, object);
}
if (error.code === 'ENOENT') {
return callback(null, JSON.stringify({}));
}
if (error.code === 'EPERM' && times < 10) {
setTimeout(function () {
readFile(fileName, callback, times + 1);
}, 1000);
return;
}
return callback(error);
});
};
const readFileSync = function (fileName, times) {
times = times || 0;
try {
return fs.readFileSync(fileName);
} catch (error) {
if (error.code === 'ENOENT') {
return JSON.stringify({});
}
if (error.code === 'EPERM' && times < 10) {
return readFileSync(fileName, times + 1);
}
throw error;
}
};
/**
* @summary Get the default data path
* @function
* @public
*
* @description
* This function will return `null` when running in the
* renderer process without support for the `remote` IPC
* mechanism. You have to explicitly set a data path using
* `.setDataPath()` in these cases.
*
* @returns {(String|Null)} default data path
*
* @example
* const defaultDataPath = storage.getDefaultDataPath()
*/
exports.getDefaultDataPath = utils.getDefaultDataPath;
/**
* @summary Set current data path
* @function
* @public
*
* @description
* The default value will be used if the directory is undefined.
*
* @param {(String|Undefined)} directory - directory
*
* @example
* const os = require('os');
* const storage = require('electron-json-storage');
*
* storage.setDataPath(os.tmpdir());
*/
exports.setDataPath = utils.setDataPath;
/**
* @summary Get current user data path
* @function
* @public
*
* @description
* Returns the current data path. It defaults to a directory called
* "storage" inside Electron's `userData` path.
*
* @returns {String} the user data path
*
* @example
* const storage = require('electron-json-storage');
*
* const dataPath = storage.getDataPath();
* console.log(dataPath);
*/
exports.getDataPath = utils.getDataPath;
/**
* @summary Read user data
* @function
* @public
*
* @description
* If the key doesn't exist in the user data, an empty object is returned.
* Also notice that the `.json` extension is added automatically, but it's
* ignored if you pass it yourself.
*
* Passing an extension other than `.json` will result in a file created
* with both extensions. For example, the key `foo.data` will result in a file
* called `foo.data.json`.
*
* @param {String} key - key
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {Function} callback - callback (error, data)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.get('foobar', function(error, data) {
* if (error) throw error;
*
* console.log(data);
* });
*/
exports.get = function (key, options, callback) {
if (_.isFunction(options)) {
callback = options;
}
options = options || {};
callback = callback || _.noop;
var fileName = null;
async.waterfall([
async.asyncify(_.partial(utils.getFileName, key, {
dataPath: options.dataPath
})),
function (result, callback) {
fileName = result;
mkdirp(path.dirname(fileName), callback);
},
function (made, next) {
lock.lock(utils.getLockFileName(fileName), function (error) {
if (error && error.code === 'EEXIST') {
return exports.get(key, options, callback);
}
return next(error);
});
},
function (callback) {
readFile(fileName, callback);
},
function (object, callback) {
var objectJSON = {};
try {
objectJSON = JSON.parse(object);
} catch (error) {
return callback(new Error('Invalid data: ' + object));
}
return callback(null, objectJSON);
}
], function (error, result) {
lock.unlock(utils.getLockFileName(fileName), function (lockError) {
if (error) {
return callback(error);
}
return callback(lockError, result);
});
});
};
/**
* @summary Read user data (sync)
* @function
* @public
*
* @description
* See `.get()`.
*
* @param {String} key - key
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
*
* @example
* const storage = require('electron-json-storage');
*
* var data = storage.getSync('foobar');
* console.log(data);
*/
exports.getSync = function (key, options) {
options = options || {};
var fileName = utils.getFileName(key, {
dataPath: options.dataPath
});
mkdirp.sync(path.dirname(fileName));
try {
lock.lockSync(utils.getLockFileName(fileName));
} catch (error) {
if (error && error.code === 'EEXIST') {
return exports.getSync(key, options);
}
throw error;
}
var object = readFileSync(fileName);
lock.unlockSync(utils.getLockFileName(fileName));
try {
return JSON.parse(object);
} catch (error) {
throw new Error('Invalid data: ' + object);
}
};
/**
* @summary Read many user data keys
* @function
* @public
*
* @description
* This function returns an object with the data of all the passed keys.
* If one of the keys doesn't exist, an empty object is returned for it.
*
* @param {String[]} keys - keys
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {Function} callback - callback (error, data)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.getMany([ 'foobar', 'barbaz' ], function(error, data) {
* if (error) throw error;
*
* console.log(data.foobar);
* console.log(data.barbaz);
* });
*/
exports.getMany = function (keys, options, callback) {
if (_.isFunction(options)) {
callback = options;
options = {};
}
options = options || {};
callback = callback || _.noop;
async.reduce(keys, {}, function (reducer, key, callback) {
exports.get(key, options, function (error, data) {
if (error) {
return callback(error);
}
return callback(null, _.set(reducer, key, data));
});
}, callback);
};
/**
* @summary Read all user data
* @function
* @public
*
* @description
* This function returns an empty object if there is no data to be read.
*
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {Function} callback - callback (error, data)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.getAll(function(error, data) {
* if (error) throw error;
*
* console.log(data);
* });
*/
exports.getAll = function (options, callback) {
if (_.isFunction(options)) {
callback = options;
options = {};
}
options = options || {};
callback = callback || _.noop;
async.waterfall([
_.partial(exports.keys, options),
function (keys, callback) {
async.reduce(keys, {}, function (reducer, key, callback) {
async.waterfall([
_.partial(exports.get, key, options),
function (contents, callback) {
return callback(null, _.set(reducer, key, contents));
}
], callback);
}, callback);
}
], callback);
};
/**
* @summary Write user data
* @function
* @public
*
* @param {String} key - key
* @param {Object} json - json object
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {String} [options.validate] - validate writes by reading the data back
* @param {boolean} [options.prettyPrinting] - adds line breaks and spacing to the written data
* @param {Function} callback - callback (error)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.set('foobar', { foo: 'bar' }, function(error) {
* if (error) throw error;
* });
*/
exports.set = function (key, json, options, callback, retries) {
if (!_.isNumber(retries)) {
retries = 10;
}
if (_.isFunction(options)) {
callback = options;
}
options = options || {};
callback = callback || _.noop;
var fileName = null;
async.waterfall([
async.asyncify(_.partial(utils.getFileName, key, {
dataPath: options.dataPath
})),
function (result, callback) {
fileName = result;
const data = JSON.stringify(json, null, (options.prettyPrinting ? 2 : 0));
if (!data) {
return callback(new Error('Invalid JSON data'));
}
// Create the directory in case it doesn't exist yet
mkdirp(path.dirname(fileName), function (error) {
return callback(error, data);
});
},
function (data, next) {
lock.lock(utils.getLockFileName(fileName), function (error) {
if (error && error.code === 'EEXIST') {
return exports.set(key, json, options, callback);
}
return next(error, fileName, data);
});
},
function (fileName, data, callback) {
writeFileAtomic(fileName, data, callback);
}
], function (error) {
lock.unlock(utils.getLockFileName(fileName), function (lockError) {
if (error) {
return callback(error);
}
if (!options.validate) {
return callback(lockError);
}
// Check that the writes were actually successful
// after a little bit
setTimeout(function () {
exports.get(key, {
dataPath: options.dataPath
}, function (getError, data) {
if (getError) {
return callback(getError);
}
if (!_.isEqual(data, json)) {
if (retries <= 0) {
throw new Error('Couldn\'t ensure data was written correctly');
}
return exports.set(key, json, options, callback, retries - 1);
}
return callback();
});
}, 100);
});
});
};
/**
* @summary Write user data sync
* @function
* @public
*
* @param {String} key - key
* @param {Object} json - json object
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {boolean} [options.prettyPrinting] - adds line breaks and spacing to the written data
*
* @example
* const storage = require('electron-json-storage');
*
* storage.setSync('foobar', { foo: 'bar' });
*/
exports.setSync = function (key, json, options = {}) {
const fileName = utils.getFileName(key, {
dataPath: options.dataPath
});
const data = JSON.stringify(json, null, (options.prettyPrinting ? 2 : 0));
if (!data) {
throw new Error('Invalid JSON data');
}
mkdirp.sync(path.dirname(fileName));
try {
lock.lockSync(utils.getLockFileName(fileName));
} catch (error) {
if (error && error.code === 'EEXIST') {
return exports.setSync(key, json, options);
}
throw error;
}
try {
fs.writeFileSync(fileName, data);
lock.unlockSync(utils.getLockFileName(fileName));
return;
}
catch (error) {
throw error;
}
};
/**
* @summary Check if a key exists
* @function
* @public
*
* @param {String} key - key
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {Function} callback - callback (error, hasKey)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.has('foobar', function(error, hasKey) {
* if (error) throw error;
*
* if (hasKey) {
* console.log('There is data stored as `foobar`');
* }
* });
*/
exports.has = function (key, options, callback) {
if (_.isFunction(options)) {
callback = options;
}
options = options || {};
callback = callback || _.noop;
async.waterfall([
async.asyncify(_.partial(utils.getFileName, key, {
dataPath: options.dataPath
})),
function (filename, done) {
fs.stat(filename, function (error) {
if (error) {
if (error.code === 'ENOENT') {
return done(null, false);
}
return done(error);
}
return done(null, true);
});
}
], callback);
};
/**
* @summary Get the list of saved keys
* @function
* @public
*
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {Function} callback - callback (error, keys)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.keys(function(error, keys) {
* if (error) throw error;
*
* for (var key of keys) {
* console.log('There is a key called: ' + key);
* }
* });
*/
exports.keys = function (options, callback) {
if (_.isFunction(options)) {
callback = options;
options = {};
}
options = options || {};
callback = callback || _.noop;
async.waterfall([
function (callback) {
callback(null, options.dataPath || exports.getDataPath());
},
function (userDataPath, callback) {
mkdirp(userDataPath, function (error) {
return callback(error, userDataPath);
});
},
fs.readdir,
function (keys, callback) {
callback(null, _.map(_.reject(keys, function (key) {
return path.extname(key) !== '.json';
}), function (key) {
return path.basename(decodeURIComponent(key), '.json');
}));
}
], callback);
};
/**
* @summary Remove a key
* @function
* @public
*
* @description
* Notice this function does nothing, nor throws any error
* if the key doesn't exist.
*
* @param {String} key - key
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {Function} callback - callback (error)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.remove('foobar', function(error) {
* if (error) throw error;
* });
*/
exports.remove = function (key, options, callback) {
if (_.isFunction(options)) {
callback = options;
}
options = options || {};
callback = callback || _.noop;
async.waterfall([
async.asyncify(_.partial(utils.getFileName, key, {
dataPath: options.dataPath
})),
rimraf
], callback);
};
/**
* @summary Clear all stored data in the current user data path
* @function
* @public
*
* @param {Object} [options] - options
* @param {String} [options.dataPath] - data path
* @param {Function} callback - callback (error)
*
* @example
* const storage = require('electron-json-storage');
*
* storage.clear(function(error) {
* if (error) throw error;
* });
*/
exports.clear = function (options, callback) {
if (_.isFunction(options)) {
callback = options;
}
options = options || {};
callback = callback || _.noop;
const userData = options.dataPath || exports.getDataPath();
const jsonFiles = path.join(userData, '*.json');
rimraf(jsonFiles, callback);
};