Background
I am working on a MEAN stack project, which needs to store some data in browser's localStorage.
Since there is limitation on the capacity of localStorage(several megaBytes) and the data volumn is not predictable, I have to handle this problem.
Similar to this answer: make localStorage or sessionStorage expire like cookies [duplicate], I made some common functions for getting/setting items in localStorage. Every item contains an _expires
field to indicate when the item will be expired. This filed will be checked when the getLocalStorageItem
function is called, if expired, the item will be removed.
angular.module('ca.interaction').factory('CommonService', function() {
return {
// Check expired time before getting item from localStorage
getLocalStorageItem: function (name) {
var v = localStorage.getItem(name);
try {
if (v) {
var v2 = JSON.parse(v);
var now = new Date().getTime();
if (v2._expires && v2._expires >= now) {
return v2._val;
} else if (v2._expires && v2._expires < now) {
localStorage.removeItem(name);
return "";
} else {
return v;
}
} else {
return "";
}
} catch (e) {
return v;
}
},
// Set expire time when storing an item
saveLocalStorageItem: function (name, value, expires) {
var expiresDateTime = new Date().getTime() + expires;
localStorage.setItem( name, JSON.stringify({_val: value, _expires: expiresDateTime}) );
},
removeLocalStorageItem: function (name) {
localStorage.removeItem(name);
}
}
});
Problem
If the program stores items into localStorage in a high frequency and all of them are not expired yet, the capacity limitation will be exceed.
So my original idea is to implement a FIFO(First In First Out) mechanism: use a sorted queue data Structure to hold all the keys and their Creation time(keys are sorted by Creation time from oldest to youngest). When the localStorage is full and the program continue to store a new item, the oldest key will be kicked out of the queue and the item corresponding to the key will be removed from localStorage.
But I meet some technical difficulties:
- How can I get all existing keys from localStorage? Because I may need to re-construct the queue when user refreshes browser and the program reloads. I read Storage API in MDN but no API can do this.
- How can I know how much free space remaining in localStorage? Because before storing a new item, I need to do a calculation and know how many oldest items should be removed.
I am not sure if any existing library/framework can achieve this goal, please share your advice