-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_storage.js
62 lines (55 loc) · 1.57 KB
/
file_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
var fs = require('fs-extra');
var path = require('path');
var touch = require("touch");
const MASTER_KEY_FILE_NAME = '__allKeys';
const DEFAULT_ENCODING = 'utf8';
var touchFile = function(filepath) {
var dirpath = path.dirname(filepath);
try {
fs.accessSync(dirpath, fs.F_OK);
} catch(err) {
fs.mkdirpSync(dirpath);
}
touch.sync(filepath);
};
module.exports = function(pathToUse) {
var getMasterKeyFile = function() {
var fileName = path.join(pathToUse, MASTER_KEY_FILE_NAME);
touchFile(fileName);
return fileName;
};
var blockFileName = function(block) {
return path.join(pathToUse, block);
};
return {
clearBlock : function(block) {
const fileName = blockFileName(block);
fs.removeSync(fileName);
},
readBlock : function(block) {
const fileName = blockFileName(block);
var data = fs.readFileSync(fileName, DEFAULT_ENCODING);
if(!data) {
return {};
}
return JSON.parse(data);
},
writeMasterBlock : function(list, version) {
const fileName = getMasterKeyFile();
touchFile(fileName);
return fs.writeFileSync(fileName, JSON.stringify({version: version, items: list}));
},
readMasterBlock : function() {
var data = fs.readFileSync(getMasterKeyFile(), DEFAULT_ENCODING);
if(data !== '') {
return JSON.parse(data);
}
return undefined;
},
writeBlock : function(list, block) {
const fileName = blockFileName(block);
touchFile(fileName);
return fs.writeFileSync(fileName, JSON.stringify(list));
}
};
};