-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-handler.js
61 lines (48 loc) · 1.52 KB
/
file-handler.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
import fs from "fs";
import trash from "trash";
const mapDir = "maps/";
export let lastMap = fs.readFileSync("last-map.txt", "utf-8").replace(".json", "").replace("\n", "").replace("\r", "");
export let subscribedOnFileChange = [];
export let fileContent;
loadMap(lastMap);
export function subscribeOnFileChange(method) {
subscribedOnFileChange.push(method);
}
export function loadMap(name) {
console.log(name)
saveLastMap(name)
fileContent = getMapContent(name);
notifyServices();
}
function notifyServices() {
subscribedOnFileChange.forEach(service => service());
}
export function saveLastMap(name) {
lastMap = name;
fs.writeFileSync("last-map.txt", name + ".json");
}
export function getMapContent(name) {
let filename = name ? name + ".json" : lastMap;
return JSON.parse(fs.readFileSync(mapDir + filename, "utf-8"));
}
export function deleteMap(name) {
if (lastMap.replace(".json", "") === name)
throw new Error("You cannot delete the last or current map");
trash(mapDir + name + ".json");
}
export function getAllMaps() {
return fs.readdirSync(mapDir).map(a => {
return {
name: a.replace(".json", ""),
selected: a === lastMap + ".json"
}
});
}
export function setFileContent(content) {
fileContent = {...fileContent, ...content};
console.log("Saving", fileContent);
saveCurrentMap(lastMap);
}
export function saveCurrentMap(filename) {
fs.writeFileSync(mapDir + filename + ".json", JSON.stringify(fileContent));
}