-
Notifications
You must be signed in to change notification settings - Fork 29
/
cache.js
44 lines (36 loc) · 960 Bytes
/
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
const fs = require('fs');
// A global to store the cache data in memory
let lazyImagesCache = {};
// Loads the cache data into memory
exports.load = (cacheFile) => {
if (!cacheFile) {
return;
}
try {
if (fs.existsSync(cacheFile)) {
const cachedData = fs.readFileSync(cacheFile, 'utf8');
lazyImagesCache = JSON.parse(cachedData);
}
} catch (e) {
console.error('LazyImages - cacheFile', e);
}
};
// Reads the cached data for an image
exports.read = (imageSrc) => {
if (imageSrc in lazyImagesCache) {
return lazyImagesCache[imageSrc];
}
return undefined;
};
// Updates image data in the cache
exports.update = (cacheFile, imageSrc, imageData) => {
lazyImagesCache[imageSrc] = imageData;
if (cacheFile) {
const cacheData = JSON.stringify(lazyImagesCache);
fs.writeFile(cacheFile, cacheData, (err) => {
if (err) {
console.error('LazyImages - cacheFile', err);
}
});
}
};