-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
61 lines (52 loc) · 1.54 KB
/
utils.ts
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 * as fs from 'fs';
import * as path from 'path';
import childProcess from 'child_process';
const DBPath = path.join(__dirname, 'db.json');
export async function getAllFolders() {
if (!fs.existsSync(DBPath)) {
fs.writeFileSync(DBPath, '[]');
}
return JSON.parse(fs.readFileSync(DBPath).toString()) as Array<any>;
}
export async function addToDB(data: any) {
const db = await getAllFolders();
return new Promise<void>((resolve, reject) => {
if (!fs.existsSync(data.folderPath)) {
return reject({
folderPath: true,
message: 'This path is not found on your device.',
});
}
if (
db.some(
(item) => item.folderPath.split('\\').join('\\') === data.folderPath,
)
) {
return reject({
folderPath: true,
message: 'This path is already watched.',
});
}
db.push({ ...data, timestamps: Date.now() });
fs.writeFile(DBPath, JSON.stringify(db), function callback(error) {
if (error) return reject(error);
resolve();
});
});
}
export async function removeFromDB(data: any) {
let db = await getAllFolders();
db = db.filter((item) => item.folderPath !== data.folderPath);
return new Promise<void>((resolve, reject) => {
fs.writeFile(DBPath, JSON.stringify(db), function callback(error) {
if (error) return reject(error);
resolve();
});
});
}
export function openFolder(
folderPath: string,
callback: (error: childProcess.ExecException | null) => void,
) {
childProcess.exec(`start "" "${folderPath}"`, callback);
}