-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
95 lines (87 loc) · 2.07 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
var fs = require('fs')
var path = require('path')
var rimraf = require('rimraf')
function createSimpleStorage () {
var dir = path.join.apply(path, arguments)
function fileName (name) {
return path.resolve(dir, name + '.json')
}
/**
* Delete the storage directory.
*/
function reset () {
rimraf.sync(dir)
}
function resetPromise () {
return new Promise(function (resolve, reject) {
rimraf(dir, function (error) {
if (error) {
return reject(error)
}
resolve(error)
})
})
}
/**
* Serialize and save a file to the storage directory.
*/
function save (name, data) {
fs.mkdirSync(dir, { recursive: true })
try {
fs.writeFileSync(fileName(name), JSON.stringify(data, null, 2))
} catch (e) {
// TODO: write this error in a log
}
}
function savePromise (name, data) {
return fs.promises.mkdir(dir, { recursive: true })
.then(function () {
return fs.promises.writeFile(fileName(name), JSON.stringify(data, null, 2))
})
.catch(function () {
// TODO: write this error in a log
})
}
/**
* Read and unserialize a file from the storage directory.
*/
function get (name) {
var file = fileName(name)
try {
var fileData = fs.readFileSync(file, 'utf8')
} catch (e) {
// TODO: write this error in a log
return null
}
try {
return JSON.parse(fileData)
} catch (e) {
// TODO: write this error in a log
return null
}
}
function getPromise (name) {
return fs.promises.readFile(fileName(name), 'utf8')
.then(function (fileData) {
return JSON.parse(fileData)
})
.catch(function () {
// TODO: write this error in a log
return null
})
}
return {
dir: dir,
reset: reset,
save: save,
get: get,
promises: {
dir: dir,
reset: resetPromise,
save: savePromise,
get: getPromise
}
}
}
createSimpleStorage.userDir = process.env.HOME || process.env.USERPROFILE
module.exports = createSimpleStorage