Cache, counters and small stores
Reference of CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() and RESTORE().
On this page
Global functions for small amounts of data: the in-memory cache (CACHE() and F.cache), file caches, preferences, persistent objects, counters, two extra NoSQL stores and backups of folders. In this reference counter is an instance returned by COUNTER(). The guide Cache, counters and small stores explains how to use them with examples.
API
method
CACHE(key, [value], [expire])
Reads or saves a value in the in-memory cache.
CACHE(key, [value], [expire])| Parameter | Type | Description |
|---|---|---|
key |
String |
The key of the value. |
value? |
Object |
The value to save. Leave it out to read. |
expire? |
String|Date |
A text such as '5 minutes' or '1 hour', or a Date. Without it the value expires in 5 minutes. Default: '5 minutes' |
Returns Object The cached value.
With one argument the function returns the cached value, or undefined when the key does not exist or has expired. With more arguments it saves the value and returns it. It is a short form of F.cache.get2() and F.cache.set().
The cache lives in the memory of the process and is empty after a restart (unless allow_cache_snapshot is enabled).
function list() {
var $ = this;
var items = CACHE('products');
if (items) {
$.json(items);
return;
}
NOSQL('products').find().callback(function(err, response) {
CACHE('products', response, '10 minutes');
$.json(response);
});
}
property
F.cache
The in-memory cache of the app.
F.cacheReturns Object The cache instance.
The object behind CACHE(). Its items are in F.cache.items, an object where each key holds { value, expire }. Once a minute Total.js removes expired items and emits cache_expired for each of them.
var count = Object.keys(F.cache.items).length;
method
F.cache.set(key, value, [expire])
Saves a value to the cache.
F.cache.set(key, value, [expire])| Parameter | Type | Description |
|---|---|---|
key |
String |
The key of the value. |
value |
Object |
The value to save. |
expire? |
String|Date |
A text such as '5 minutes' or '1 hour', or a Date. Without it the value expires in 5 minutes. Default: '5 minutes' |
Returns Object The saved value.
Replaces an existing value with the same key and emits the event cache_set. F.cache.add() is the same method. With allow_cache_cluster the value is sent to the other processes of the cluster.
F.cache.set('user_' + user.id, user, '1 hour');
method
F.cache.get(key, [def])
Reads a value from the cache.
F.cache.get(key, [def])| Parameter | Type | Description |
|---|---|---|
key |
String |
The key of the value. |
def? |
Object |
The value to return when nothing is cached. Default: undefined |
Returns Object The cached value or def.
Returns def when the key does not exist or the value has expired. An expired value is removed and the event cache_expired is emitted. F.cache.read() is the same method.
var user = F.cache.get('user_' + id, null);
method
F.cache.get2(key, [def])
Reads a value from the cache without updating the current time.
F.cache.get2(key, [def])| Parameter | Type | Description |
|---|---|---|
key |
String |
The key of the value. |
def? |
Object |
The value to return when nothing is cached. Default: undefined |
Returns Object The cached value or def.
Works like F.cache.get(), but compares the expiration with the global NOW, which Total.js updates periodically, instead of a new Date. It is a little faster and an item can stay valid for a few seconds longer. CACHE(key) uses it. F.cache.read2() is the same method.
var rates = F.cache.get2('rates', {});
method
F.cache.remove(key)
Removes one value from the cache.
F.cache.remove(key)| Parameter | Type | Description |
|---|---|---|
key |
String |
The key of the value. |
Returns Object The removed item { value, expire }, or undefined.
With allow_cache_cluster the removal is sent to the other processes of the cluster.
NOSQL('users').modify(model).id(model.id).callback(function() {
F.cache.remove('user_' + model.id);
});
method
F.cache.removeAll(search)
Removes all values whose key contains a text or matches a regular expression.
F.cache.removeAll(search)| Parameter | Type | Description |
|---|---|---|
search |
String|RegExp |
A part of the key, or a regular expression. |
Returns Number The number of removed items.
A text removes every key that contains it; a RegExp removes every key it matches. To remove everything use F.cache.clear(). F.cache.reset() is the same method.
var count = F.cache.removeAll('user_');
F.cache.removeAll(/^product_\d+$/);
method
F.cache.clear()
Removes every value from the cache.
F.cache.clear()Returns Object The cache, for chaining.
With allow_cache_cluster the other processes of the cluster are cleared too.
F.cache.clear();
method
F.cache.setExpire(key, expire)
Changes the expiration of a cached value.
F.cache.setExpire(key, expire)| Parameter | Type | Description |
|---|---|---|
key |
String |
The key of the value. |
expire |
String|Date |
A text such as '1 hour', or a Date. |
Returns Object The cache, for chaining.
Does nothing when the key does not exist.
F.cache.setExpire('session_' + id, '30 minutes');
method
F.cache.fn(key, maker, [callback], [options])
Returns a cached value or creates it with a function.
F.cache.fn(key, maker, [callback], [options])| Parameter | Type | Description |
|---|---|---|
key |
String |
The key of the value. |
maker |
Function |
function(next, options) that creates the value and calls next(value, [expire]). |
callback? |
Function |
function(value, fromcache, options). |
options? |
Object |
Any object, passed to both functions. |
Returns Object The cache, for chaining.
When the key holds a value, callback(value, true, options) is called at once. Otherwise maker(next, options) runs; call next(value, [expire]) to cache the value, and then callback(value, false, options) is called. A falsy value (false, 0, '', null) is not considered cached.
function stats() {
var $ = this;
F.cache.fn('stats', function(next) {
NOSQL('orders').count().callback(function(err, count) {
next({ orders: count }, '5 minutes');
});
}, function(value) {
$.json(value);
});
}
method
FILECACHE(id, expire, callback, maker, [encoding])
Returns a value cached in a file, or creates it.
FILECACHE(id, expire, callback, maker, [encoding])| Parameter | Type | Description |
|---|---|---|
id |
String |
The identifier of the cached value. |
expire |
String |
How long the file is valid, for example '1 hour' or '2 days'. |
callback |
Function |
function(err, value). |
maker |
Function |
function(next, id) that creates the value and calls next(err, value, [load]). |
encoding? |
String |
'json', or the encoding of a text value such as 'utf8'. Default: 'json' |
The value is stored in the tmp/ folder in a file named after a hash of id. When the file does not exist or is older than expire, maker(next, id) runs. Call next(err, value, [load]): without an error the value is written to the file, and callback(err, value) is called unless load is false. Otherwise the file is read and passed to callback(err, value).
By default the value is saved as JSON and parsed back (dates included). With another encoding, for example 'utf8', the value is written as it is and read as a text.
FILECACHE('countries', '1 day', function(err, countries) {
console.log(countries.length);
}, function(next) {
RESTBuilder.GET('https://example.com/countries.json').callback(next);
});
method
MEMORIZE([name], [delay], [skip])
since 0.0.46
Returns an object that is saved to a JSON file.
MEMORIZE([name], [delay], [skip])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The name of the file. Default: '' |
delay? |
Number |
Milliseconds between save() and the write. Default: 10000 |
skip? |
String|Array |
Keys that are not written to the file, as an array or a text separated by commas. |
Returns Object The stored object with a save() method.
Reads databases/memorize_{name}.json (or databases/memorize.json without a name) synchronously and returns its content as an object, or an empty object when the file does not exist. The object has a method save() that writes it back.
Each call reads the file again and returns a new object, so call it once and keep the reference. The delay and skip arguments can be passed in any order. The databases folder must exist.
var state = MEMORIZE('importer', 'running');
state.lastrun = NOW;
state.running = true; // not saved
state.save();
method
data.save()
since 0.0.46
Writes the object of MEMORIZE() to its file.
data.save()The write happens after the delay given to MEMORIZE() (10 seconds by default). Another save() within that time restarts the delay, so a burst of changes gives one write. The object is written as formatted JSON; functions and the keys in skip are left out.
var counters = MEMORIZE('counters', 1000);
counters.downloads = (counters.downloads || 0) + 1;
counters.save();
property
PREF
Preferences of the app that are saved to a file.
PREFReturns Object The preferences.
Total.js loads databases/preferences.json at start and copies each value to PREF, so you read a preference as a property: PREF.token. In a thread the file is databases/preferences_{thread}.json. Change values only with PREF.set(), PREF.inc() and PREF.rem(); a value assigned directly is not saved. Do not use the names set, inc and rem.
ON('ready', function() {
if (!PREF.installed) {
// first start
PREF.set('installed', NOW);
}
});
method
PREF.set(name, [value])
Saves a preference or reads it.
PREF.set(name, [value])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the preference. |
value? |
Object |
The new value, or null to remove it. |
Returns Object The value.
Without value the function returns the current value. With a value it saves it to PREF and writes all preferences one second after the last change (through DEF.onPrefSave). null removes the preference, like PREF.rem().
PREF.set('token', GUID(30));
console.log(PREF.token);
method
PREF.inc(name, [value])
Adds a number to a preference.
PREF.inc(name, [value])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the preference. |
value? |
Number |
The number to add. Default: 1 |
Returns Number The new value.
Starts from value when the preference does not exist. The result is saved like PREF.set().
var count = PREF.inc('imports');
PREF.inc('credits', -5);
method
PREF.rem(name)
Removes a preference from the saved file.
PREF.rem(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the preference. |
The preference is removed from PREF and the file is written again.
PREF.rem('token');
delegate
DEF.onPrefLoad = function(next) {}
Loads the preferences at start.
DEF.onPrefLoad = function(next) {}| Parameter | Type | Description |
|---|---|---|
next |
Function |
function(object) that receives the stored preferences. |
The default delegate reads databases/preferences.json and calls next(object). Replace it to keep the preferences somewhere else; call next(object) with the stored values, or next() when there are none. Assign it in a definition file: when the delegate changes while the app starts, Total.js loads the preferences again with the new one.
// definitions/preferences.js
DEF.onPrefLoad = function(next) {
NOSQL('preferences').read().callback(function(err, doc) {
next(doc ? doc.data : null);
});
};
DEF.onPrefSave = function(data) {
NOSQL('preferences').modify({ data: data }, true).where('id', 'app');
};
delegate
DEF.onPrefSave = function(data) {}
Saves the preferences.
DEF.onPrefSave = function(data) {}| Parameter | Type | Description |
|---|---|---|
data |
Object |
All preferences. |
Called one second after the last change of a preference, with an object of all preferences. The default delegate writes it as formatted JSON to databases/preferences.json. Replace it together with DEF.onPrefLoad.
var save = DEF.onPrefSave;
DEF.onPrefSave = function(data) {
console.log('Preferences saved');
save(data);
};
method
COUNTER(name)
Returns a counter that keeps daily statistics.
COUNTER(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the counter. |
Returns Counter The counter instance.
The data is stored in databases/{name}.counter as NoSQL documents, one per id and day: { id, sum, min, max, day, month, year, ts, date }, where ts is the date as a number yyyyMMdd. The instance is created on the first call and then reused.
hit() collects values in memory. On every fifth service event (about every five minutes) the counter writes them to the file. Values that are not written yet are lost when the process stops.
The reading methods return a NoSQL query builder: pass the callback as the last argument or call .callback() on the result.
exports.install = function() {
ROUTE('GET /', index);
};
function index() {
COUNTER('visits').hit('homepage');
this.view('index');
}
method
counter.hit(id, [value])
Adds a value to the counter of today.
counter.hit(id, [value])| Parameter | Type | Description |
|---|---|---|
id |
String |
What you count, for example a page or a product. |
value? |
Number |
The value to add. Default: 1 |
Returns Counter The counter, for chaining.
The value is added to the sum of id for the current day. The counter also keeps the smallest and the largest single value as min and max.
COUNTER('sales').hit('eshop', order.price);
COUNTER('sales').hit('orders');
method
counter.flush()
Writes the collected values to the file now.
counter.flush()Returns Counter The counter, for chaining.
The counter calls it periodically. Call it yourself before a planned stop so that no hits are lost.
ON('exit', function() {
COUNTER('visits').flush();
});
method
counter.count([id], [callback])
Returns the total sum of all stored values.
counter.count([id], [callback])| Parameter | Type | Description |
|---|---|---|
id? |
String|Array |
An id or an array of ids. |
callback? |
Function |
function(err, sum). |
Returns QueryBuilder The query builder.
Sums the sum field of all days, for one id or an array of ids, or for all ids. Values that are not flushed yet are not included.
COUNTER('visits').count('homepage', function(err, sum) {
console.log('Visits:', sum);
});
method
counter.daily(id, [callback])
Returns the stored days of one id.
counter.daily(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the counter. |
callback? |
Function |
function(err, items). |
Returns QueryBuilder The query builder.
Each item is a stored document without id: { sum, min, max, day, month, year, ts, date }. You can add conditions, sorting and paging to the returned builder.
COUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {
console.log(days);
});
method
counter.monthly(id, [callback])
Returns the values of one id grouped by month.
counter.monthly(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the counter. |
callback? |
Function |
function(err, items). |
Returns QueryBuilder The query builder.
Each item is { date, year, month, ts, sum, min, max, count }, where date is the month as text yyyyMM, ts the same as a number and count the number of stored days.
COUNTER('sales').monthly('eshop', function(err, months) {
months.forEach(m => console.log(m.year, m.month, m.sum));
});
method
counter.yearly(id, [callback])
Returns the values of one id grouped by year.
counter.yearly(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the counter. |
callback? |
Function |
function(err, items). |
Returns QueryBuilder The query builder.
Each item is { date, year, ts, sum, min, max, count }, where date is the year as text and count the number of stored days.
COUNTER('visits').yearly('homepage', console.log);
method
counter.summarize([type], [callback])
Returns totals of all ids.
counter.summarize([type], [callback])| Parameter | Type | Description |
|---|---|---|
type? |
String |
'monthly' or 'yearly'. |
callback? |
Function |
function(err, items). |
Returns QueryBuilder The query builder.
Without type you get one item per id: { id, sum, min, max, count }. With 'monthly' or 'yearly' you get one item per id and month or year, with the fields ts, date, year and (for months) month added.
COUNTER('visits').summarize(function(err, items) {
items.quicksort('sum_desc');
console.log(items.slice(0, 10));
});
method
counter.find()
Returns a query builder over the stored documents.
counter.find()Returns QueryBuilder The query builder.
Use it for reports that the other methods do not cover. The documents have the fields id, sum, min, max, day, month, year, ts and date.
COUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);
method
counter.remove([id], [callback])
Removes stored documents of one id, or all of them.
counter.remove([id], [callback])| Parameter | Type | Description |
|---|---|---|
id? |
String |
The id of the counter. |
callback? |
Function |
function(err, count). |
Returns QueryBuilder The query builder.
Without id every stored document is removed. Values that are not flushed yet stay in memory.
COUNTER('visits').remove('oldpage');
method
counter.clear()
Removes all stored data of the counter.
counter.clear()Returns Counter The counter, for chaining.
Empties the file. Values that are not flushed yet stay in memory.
COUNTER('visits').clear();
method
INMEMORY(name)
Returns a NoSQL database that keeps its documents in memory.
INMEMORY(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the database. |
Returns Database The database instance.
All documents are loaded from databases/{name}.inmemory on the first operation and kept in memory. After a change the file is written in 5 seconds. The instance is created on the first call and then reused.
It supports insert(), find(), read(), list(), count(), scalar(), modify()/update() and remove() with the query builder of NOSQL(). Keep the collection small: every document is in memory.
INMEMORY('online').insert({ id: user.id, name: user.name, dtconnected: NOW });
INMEMORY('online').count().callback(function(err, count) {
console.log(count, 'users online');
});
INMEMORY('online').remove().where('id', user.id);
method
TEXTDB(name)
Returns a NoSQL database stored in several files of a folder.
TEXTDB(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the database, or ~ followed by an absolute path to the folder. |
Returns Database The database instance.
The documents are stored in the folder databases/textdb-{name}/. New documents go to a file until it has about 512 kB, then a new file is started. The methods and the query builder are the same as NOSQL(). A name that starts with ~ is an absolute path to the folder; such an instance is not cached.
TEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });
TEXTDB('events').find().where('type', 'login').take(50).callback(console.log);
method
BACKUP(filename, path, [callback], [filter])
Packs the files of a folder into one backup file.
BACKUP(filename, path, [callback], [filter])| Parameter | Type | Description |
|---|---|---|
filename |
String|Stream |
The path of the backup file, or a writable stream. |
path |
String|Array |
A folder, or an array of paths relative to the root of the app. |
callback? |
Function |
function(err, meta) where meta is { filename, files, size }. |
filter? |
Function |
function(path, isdirectory) that returns true to include the item. |
path is a folder: all its files and subfolders are packed. It can also be an array of paths relative to the root of the app. An existing backup file is replaced. Each file is compressed with GZIP and stored as Base64 on one line, after its relative path.
The filter(path, isdirectory) function receives a relative path that starts with / (folders end with /). Return true to include the item. Sockets are skipped.
BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {
console.log('Packed', meta.files, 'files');
}, function(path, isdirectory) {
return isdirectory || !path.endsWith('.tmp');
});
method
RESTORE(filename, target, [callback], [filter])
Unpacks a backup file made by BACKUP() into a folder.
RESTORE(filename, target, [callback], [filter])| Parameter | Type | Description |
|---|---|---|
filename |
String|Stream |
The path of the backup file, or a readable stream. |
target |
String |
The folder where the files are written. |
callback? |
Function |
function(err, meta) where meta is { files, size, path }. |
filter? |
Function |
function(path, isdirectory). |
Folders that do not exist are created. Existing files with the same name are overwritten.
The filter(path, isdirectory) function receives the relative path from the backup. For a file return false to skip it, a new relative path (in an existing folder) to write it elsewhere, or nothing to keep it. For a folder return false to not create it.
RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {
console.log('Restored', meta.files, 'files', meta.size, 'bytes');
});