This repository has been archived by the owner on Jan 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
104 lines (99 loc) · 3.58 KB
/
index.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
const fs = require('graceful-fs');
const readFile = fs.readFileSync;
const writeFile = fs.writeFileSync;
const path = require('path');
class MultiFileSync {
constructor(
source,
fileExtension = 'json',
{ defaultValue = {}, serialize = JSON.stringify, deserialize = JSON.parse } = {}
) {
this.source = source;
this.fileExtension = fileExtension;
this.defaultValue = defaultValue;
this.serialize = serialize;
this.deserialize = deserialize
}
read() {
let that = this;
function readSingleFile(path) {
try {
const data = readFile(path, 'utf-8').trim();
return data ? that.deserialize(data) : {}
} catch (e) {
if (e instanceof SyntaxError) {
e.message = `Malformed JSON in file: ${that.source}\n${e.message}`
}
throw e
}
}
if (fs.existsSync(that.source)) {
let files = fs.readdirSync(this.source);
if (!files.length) {
return this.defaultValue
} else {
let result = {};
files.forEach(function(filename) {
if (filename.endsWith(that.fileExtension)) {
if (filename.includes('__')) {
const arrayName = filename.split('__')[0];
if (result[arrayName] === undefined) {
result[arrayName] = []
}
result[arrayName].push(
readSingleFile(path.join(that.source, filename))
)
} else {
result[path.parse(filename).name] = readSingleFile(
path.join(that.source, filename)
)
}
}
});
return result
}
}
return this.defaultValue
}
write(data) {
if (!fs.existsSync(this.source)) {
throw Error('source does not exists')
}
if (!fs.lstatSync(this.source).isDirectory()) {
throw Error('source is not a folder')
}
let files = fs.readdirSync(this.source);
let that = this;
files.forEach(function(filename) {
if (filename.endsWith(that.fileExtension)) {
fs.unlinkSync(path.join(that.source, filename))
}
});
if (data !== undefined) {
for (let [key, value] of Object.entries(data)) {
if (Array.isArray(value)) {
Object.entries(value).forEach(([, value], index) => {
let fileDiscriminator = index;
if (value.id !== undefined) {
fileDiscriminator = value.id
}
writeFile(
path.join(
this.source,
key + '__' + fileDiscriminator + '.' + this.fileExtension
),
this.serialize(value)
)
})
} else {
writeFile(
path.join(this.source, key + '.' + this.fileExtension),
this.serialize(value)
)
}
}
}
return true
}
}
module.exports = MultiFileSync;