-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-localstorage.js
83 lines (83 loc) · 2.19 KB
/
json-localstorage.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
"use strict";
var fs = require("fs");
var path = require("path");
var config = require('./package.json').config;
var LocalStorage;
(function (LocalStorage) {
LocalStorage.length = getLength();
function getItem(key) {
return getStoredItems()[key] || null;
}
LocalStorage.getItem = getItem;
function setItem(key, value) {
var obj = getStoredItems();
obj[key] = value;
LocalStorage.length = countKeys(obj);
writeFile(obj);
}
LocalStorage.setItem = setItem;
function removeItem(key) {
var obj = getStoredItems();
delete obj[key];
LocalStorage.length = countKeys(obj);
writeFile(obj);
}
LocalStorage.removeItem = removeItem;
function clear() {
LocalStorage.length = 0;
writeFile({});
return undefined;
}
LocalStorage.clear = clear;
function getLength() {
return countKeys(getStoredItems());
}
LocalStorage.getLength = getLength;
function countKeys(obj) {
var size = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key))
size++;
}
return size;
}
function key(n) {
var obj = getStoredItems();
var counter = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (n == counter) {
return key;
}
else if (counter > n) {
return null;
}
counter++;
}
}
return null;
}
LocalStorage.key = key;
;
function getStoredItems() {
try {
return JSON.parse(readFile());
}
catch (e) {
return {};
}
}
function readFile() {
return fs.readFileSync(getFilepath(), getFileOptions());
}
function writeFile(obj) {
return fs.writeFileSync(getFilepath(), JSON.stringify(obj), getFileOptions());
}
function getFilepath() {
return path.join(__dirname, config.filepath);
}
function getFileOptions() {
return { "encoding": "utf8" };
}
})(LocalStorage || (LocalStorage = {}));
module.exports = LocalStorage;