-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-cache.js
111 lines (99 loc) · 2.79 KB
/
file-cache.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const { existsSync, readFileSync, writeFileSync, unlinkSync } = require('fs');
const { join } = require('path');
const { tmpdir } = require('os');
class FileCache {
#filename;
#cache;
/**
* Creates an instance of FileCache.
* @param {string} [filename] - Optional custom filename for the cache.
* @param {string} [filepath] - Optional custom file path for the cache.
* @throws {Error} Throws an error if the provided filename contains invalid characters.
*/
constructor(filename, filepath) {
if (filename && !filename.match(/^[^.\s\\/]+$/))
throw new Error('Invalid filename provided. Filename must not contain spaces or special characters.');
this.#filename = join(
`${filepath ? filepath : tmpdir()}`,
`${filename ? `${filename}.json` : 'file_cache.json'}`);
this.#cache = {};
this.#loadCache();
}
#loadCache() {
try {
if (existsSync(this.#filename)) {
const data = readFileSync(this.#filename, 'utf8');
this.#cache = JSON.parse(data);
} else {
this.#cache = {};
}
} catch (error) {
console.error('[FileCache] Error loading cache:', error);
this.#cache = {};
}
}
#saveCache() {
try {
writeFileSync(this.#filename, JSON.stringify(this.#cache, null, 4), 'utf8');
} catch (error) {
console.error('[FileCache] Error saving cache:', error);
}
}
/**
* Checks if the cache contains a value for the given key.
* @param {string} key - The cache key to check.
* @returns {boolean} Returns true if the cache has a value for the key, false otherwise.
*/
has(key) {
return key in this.#cache;
}
/**
* Sets a value in the cache for the given key.
* @param {string} key - The cache key.
* @param {*} value - The value to be cached.
*/
set(key, value) {
this.#cache[key] = value;
this.#saveCache();
}
/**
* Retrieves a value from the cache for the given key.
* @param {string} key - The cache key.
* @returns {*} The cached value.
*/
get(key) {
return this.#cache[key];
}
/**
* Retrieves and removes the value from the cache for the given key.
* @param {string} key - The cache key.
* @returns {*} The cached value.
*/
take(key) {
const value = this.get(key);
this.delete(key);
return value;
}
/**
* Removes the value from the cache for the given key.
* @param {string} key - The cache key.
*/
delete(key) {
delete this.#cache[key];
this.#saveCache();
}
/**
* Clears the cache by removing all key-value pairs.
*/
clear() {
try {
this.#cache = {};
if (existsSync(this.#filename)) {
unlinkSync(this.#filename);
}
} catch (error) {
console.error('[FileCache] Error loading cache:', error);
}
}
}
module.exports = FileCache;