-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.file.js
79 lines (64 loc) · 1.92 KB
/
storage.file.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
const fs = require('fs');
const path = require('path');
let DATA_FOLDER = './data/'
let L = console.log; // log to console by default
function setProps(opt) { // {
// dataFolder, // {String}
// logger, // {Function}
// }
if (opt && opt.dataFolder) {
L(`kv30.file DATA_FOLDER was updated [${opt.dataFolder}]`);
DATA_FOLDER = opt.dataFolder
}
if (opt && opt.logger) {
if (typeof opt.logger !== 'function') {
L('kv30.file.opt.logger is not a function');
} else {
L('kv30.file logger was updated');
L = opt.logger
}
}
}
// Get random string of length N
// (from https://stackoverflow.com/a/77486780/4486609)
function _rnd(n) {
return Array.from({ length: n }, i => String.fromCharCode(Math.round(Math.ceil(Math.random() * 25) + 65))).join('');
}
async function connect()
{
// check existance of DATA_FOLDER and create one if not exists and not readonly
if (!fs.existsSync(DATA_FOLDER)) {
L('kv30.file DATA_FOLDER does not exists, will create one');
fs.mkdirSync(DATA_FOLDER, {recursive: true});
} else {
L('kv30.file DATA_FOLDER ok');
}
// is it possible to create file at DATA_FOLDER
let fn = path.join(DATA_FOLDER, 'tmp.'+_rnd(13)+'.json');
fs.writeFileSync(fn, '{}');
fs.rmSync(fn);
L('kv30.file DATA_FOLDER write access ok');
}
async function load(name) {
let fn = path.join(DATA_FOLDER, name+'.json');
return JSON.parse(fs.readFileSync(fn).toString());
}
async function save(name, data) {
return new Promise((resolve, reject) => {
let fn = path.join(DATA_FOLDER, name+'.json');
let text = JSON.stringify(data, null, 4);
fs.writeFile(fn, text, (err)=> {
if (err) {
reject(err)
} else {
resolve()
}
});
})
}
module.exports = {
setProps,
connect, // async
load, // async
save, // async
}