-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.js
49 lines (47 loc) · 1.6 KB
/
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
//==============================================================================
// ■ Database-File (fsdb/file.js)
//------------------------------------------------------------------------------
// Database file system IO opeations.
//==============================================================================
const fs = require("fs");
const path = require("path");
//------------------------------------------------------------------------------
// ● File-API
//------------------------------------------------------------------------------
function $file(fileName = "db", dirName = "") {
const filePath = path.join(__dirname, dirName, `${fileName}.json`);
return {
$filePath: filePath,
async $load() {
return new Promise((resolve, reject) => {
fs.readFile(filePath, "utf-8", (err, data) => {
if (err) {
reject(err);
} else {
resolve(JSON.parse(data));
}
});
});
},
async $save(data) {
return new Promise((resolve, reject) => {
const dataJson = JSON.stringify(data, null, 2);
if (dataJson === undefined) {
reject(new Error("Invalid data JSON format"));
} else {
fs.writeFile(filePath, dataJson, "utf-8", err => {
if (err) {
reject(err);
} else {
resolve();
}
});
}
});
}
};
}
//------------------------------------------------------------------------------
// ► Exports
//------------------------------------------------------------------------------
module.exports = $file;