Cache, counters and small stores
Keep values in the in-memory cache, in files and in preferences, count statistics, and back up folders.
On this page
Total.js has several small stores for data that does not need a full database: an in-memory cache, preferences, a persistent object, file caches, counters and two extra text databases. All of them are global functions, so every file of an app can use them.
| Function | Where the data lives | Use it for |
|---|---|---|
CACHE() / F.cache | Memory of the process | Values that expire, for example results of slow queries |
FILECACHE() | A file in the tmp/ folder | Results that should survive a restart and expire |
PREF | databases/preferences.json | Settings that the app changes at run time |
MEMORIZE() | databases/memorize_{name}.json | A plain object saved to a file |
COUNTER() | databases/{name}.counter | Daily statistics of hits or amounts |
INMEMORY() | Memory, saved to databases/{name}.inmemory | A small NoSQL collection kept in memory |
TEXTDB() | Files in databases/textdb-{name}/ | A NoSQL collection split into several files |
BACKUP() and RESTORE() pack files of a folder into one file and unpack them again. MODIFY() changes the content of views, styles, scripts and localized static files before Total.js compiles them.
The in-memory cache
CACHE(key, value, [expire]) saves a value and CACHE(key) reads it. The value is kept in the memory of the process, so it is lost after a restart. The expiration is a text such as '5 minutes' or '1 hour', or a Date. Without it the value expires in 5 minutes.
CACHE('products', items, '10 minutes');
var items = CACHE('products'); // undefined after 10 minutesF.cache is the object behind CACHE(). It has more methods:
F.cache.set('user_' + id, user, '1 hour');
F.cache.get('user_' + id, null); // the second argument is a default value
F.cache.setExpire('user_' + id, '2 hours'); // a new expiration
F.cache.remove('user_' + id);
F.cache.removeAll('user_'); // every key that contains "user_"
F.cache.clear(); // everythingTotal.js checks the cache once a minute and removes expired items. It emits the events cache_set and cache_expired (see Scheduling and events). The option allow_cache_snapshot saves the whole cache to databases/cache.json every minute and loads it at start, and allow_cache_cluster copies changes to the other processes of a cluster (see Configuration).
Read or create a value
F.cache.fn() returns a cached value or calls your function to make it. The function receives next(value, [expire]):
F.cache.fn('stats', function(next) {
NOSQL('orders').count().callback(function(err, count) {
next({ count: count }, '5 minutes');
});
}, function(value, fromcache) {
console.log(value.count, fromcache);
});A value that is false, 0, '' or null does not count as cached, so the function runs again.
A cache in a file
FILECACHE(id, expire, callback, maker, [encoding]) works like F.cache.fn(), but it saves the value to a file in the tmp/ folder. The file stays valid until it is older than expire, even after a restart. The maker function receives next(err, value):
FILECACHE('exchange-rates', '1 hour', function(err, rates) {
console.log(rates);
}, function(next) {
RESTBuilder.GET('https://example.com/rates.json').callback(next);
});The value is saved as JSON. Pass 'utf8' as encoding to keep a text as it is. See HTTP requests for RESTBuilder.
Preferences
PREF holds values that the app sets at run time and that must survive a restart, for example a token or the date of the last import. Total.js loads them at start from databases/preferences.json. Read a value as a property and write it with PREF.set():
PREF.set('last_import', NOW);
PREF.inc('imports'); // adds 1 and returns the new value
if (PREF.last_import)
console.log(PREF.last_import);Changes are written to the file one second after the last change. To keep the preferences somewhere else (for example in SQL), replace the delegates DEF.onPrefLoad and DEF.onPrefSave in a definition file.
A persistent object
MEMORIZE([name], [delay], [skip]) reads databases/memorize_{name}.json (or databases/memorize.json without a name) and returns it as an object. Change the object and call save(): Total.js writes it after delay milliseconds (10 seconds by default), so many changes give one write.
var settings = MEMORIZE('settings');
settings.theme = 'dark';
settings.save();Every call reads the file again and returns a new object: call MEMORIZE() once and keep the object. The skip argument lists keys that are not saved, for example temporary data.
Counters
COUNTER(name) counts hits or amounts per day. hit(id, [value]) adds a value in memory; about every five minutes Total.js writes the sums to databases/{name}.counter, one document per id and day with sum, min and max.
COUNTER('visits').hit('homepage');
COUNTER('sales').hit('eshop', 49.90);
COUNTER('visits').monthly('homepage', function(err, months) {
// [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }]
});Hits that are not written yet are lost if the process stops; call flush() to write them earlier.
INMEMORY and TEXTDB
INMEMORY(name) and TEXTDB(name) return a database with the same methods as NOSQL() (see NoSQL database).
INMEMORY()keeps all documents in memory and writes them todatabases/{name}.inmemory5 seconds after a change. It is fast for a small collection that is read often. It supportsinsert(),find(),read(),list(),count(),scalar(),modify()andremove().TEXTDB()keeps documents in the folderdatabases/textdb-{name}/, in several files of about 512 kB. Use it for a collection that grows.
INMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW });
INMEMORY('sessions').find().where('userid', user.id).callback(console.log);Backup and restore of files
BACKUP(filename, path, [callback], [filter]) packs all files of a folder (or a list of files) into one text file. Each file is compressed with GZIP. RESTORE(filename, target, [callback], [filter]) unpacks it into a folder.
BACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) {
console.log(meta.files, meta.size);
});
RESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) {
console.log(meta.files);
});