---
title: Cache, counters and small stores
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/caching-and-small-stores/
updated: 2026-11-16T15:41:10.817Z
---

# Cache, counters and small stores

> Reference of CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() and RESTORE().

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](../../guides/caching-and-small-stores/) explains how to use them with examples.

## API

### CACHE(key, [value], [expire])

Type: `method`

Reads or saves a value in the in-memory cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key of the value. |
| `value` | `Object` | no |  | The value to save. Leave it out to read. |
| `expire` | `String|Date` | no | `'5 minutes'` | A text such as `'5 minutes'` or `'1 hour'`, or a `Date`. Without it the value expires in 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).

Example: Cache a list
```js
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);
	});
}
```

### F.cache

Type: `property`

The in-memory cache of the app.

Returns: `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.

Example: Count cached keys
```js
var count = Object.keys(F.cache.items).length;
```

### F.cache.set(key, value, [expire])

Type: `method`

Saves a value to the cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key of the value. |
| `value` | `Object` | yes |  | The value to save. |
| `expire` | `String|Date` | no | `'5 minutes'` | A text such as `'5 minutes'` or `'1 hour'`, or a `Date`. Without it the value expires in 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.

Example: Save for one hour
```js
F.cache.set('user_' + user.id, user, '1 hour');
```

### F.cache.get(key, [def])

Type: `method`

Reads a value from the cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key of the value. |
| `def` | `Object` | no | `undefined` | The value to return when nothing is cached. |

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.

Example: Read with a default value
```js
var user = F.cache.get('user_' + id, null);
```

### F.cache.get2(key, [def])

Type: `method`

Reads a value from the cache without updating the current time.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key of the value. |
| `def` | `Object` | no | `undefined` | The value to return when nothing is cached. |

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.

Example: Read
```js
var rates = F.cache.get2('rates', {});
```

### F.cache.remove(key)

Type: `method`

Removes one value from the cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | 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.

Example: Remove after an update
```js
NOSQL('users').modify(model).id(model.id).callback(function() {
	F.cache.remove('user_' + model.id);
});
```

### F.cache.removeAll(search)

Type: `method`

Removes all values whose key contains a text or matches a regular expression.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `search` | `String|RegExp` | yes |  | 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.

Example: Remove by prefix
```js
var count = F.cache.removeAll('user_');
F.cache.removeAll(/^product_\d+$/);
```

### F.cache.clear()

Type: `method`

Removes every value from the cache.

Returns: `Object` The cache, for chaining.

With `allow_cache_cluster` the other processes of the cluster are cleared too.

Example: Clear the cache
```js
F.cache.clear();
```

### F.cache.setExpire(key, expire)

Type: `method`

Changes the expiration of a cached value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key of the value. |
| `expire` | `String|Date` | yes |  | A text such as `'1 hour'`, or a `Date`. |

Returns: `Object` The cache, for chaining.

Does nothing when the key does not exist.

Example: Extend a session
```js
F.cache.setExpire('session_' + id, '30 minutes');
```

### F.cache.fn(key, maker, [callback], [options])

Type: `method`

Returns a cached value or creates it with a function.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key of the value. |
| `maker` | `Function` | yes |  | `function(next, options)` that creates the value and calls `next(value, [expire])`. |
| `callback` | `Function` | no |  | `function(value, fromcache, options)`. |
| `options` | `Object` | no |  | 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.

Example: Cache a query
```js
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);
	});
}
```

### FILECACHE(id, expire, callback, maker, [encoding])

Type: `method`

Returns a value cached in a file, or creates it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The identifier of the cached value. |
| `expire` | `String` | yes |  | How long the file is valid, for example `'1 hour'` or `'2 days'`. |
| `callback` | `Function` | yes |  | `function(err, value)`. |
| `maker` | `Function` | yes |  | `function(next, id)` that creates the value and calls `next(err, value, [load])`. |
| `encoding` | `String` | no | `'json'` | `'json'`, or the encoding of a text value such as `'utf8'`. |

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.

Example: Cache a remote file for a day
```js
FILECACHE('countries', '1 day', function(err, countries) {
	console.log(countries.length);
}, function(next) {
	RESTBuilder.GET('https://example.com/countries.json').callback(next);
});
```

### MEMORIZE([name], [delay], [skip])

Type: `method` · Since: `0.0.46`

Returns an object that is saved to a JSON file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `''` | The name of the file. |
| `delay` | `Number` | no | `10000` | Milliseconds between `save()` and the write. |
| `skip` | `String|Array` | no |  | 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.

Example: Remember the last run
```js
var state = MEMORIZE('importer', 'running');

state.lastrun = NOW;
state.running = true; // not saved
state.save();
```

### data.save()

Type: `method` · Since: `0.0.46`

Writes the object of MEMORIZE() to its file.

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.

Example: Save after a change
```js
var counters = MEMORIZE('counters', 1000);
counters.downloads = (counters.downloads || 0) + 1;
counters.save();
```

### PREF

Type: `property`

Preferences of the app that are saved to a file.

Returns: `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`.

Example: Read a preference
```js
ON('ready', function() {
	if (!PREF.installed) {
		// first start
		PREF.set('installed', NOW);
	}
});
```

### PREF.set(name, [value])

Type: `method`

Saves a preference or reads it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the preference. |
| `value` | `Object` | no |  | 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()`.

Example: Save a token
```js
PREF.set('token', GUID(30));
console.log(PREF.token);
```

### PREF.inc(name, [value])

Type: `method`

Adds a number to a preference.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the preference. |
| `value` | `Number` | no | `1` | The number to add. |

Returns: `Number` The new value.

Starts from `value` when the preference does not exist. The result is saved like `PREF.set()`.

Example: Count imports
```js
var count = PREF.inc('imports');
PREF.inc('credits', -5);
```

### PREF.rem(name)

Type: `method`

Removes a preference from the saved file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the preference. |

The preference is removed from `PREF` and the file is written again.

Example: Remove a token
```js
PREF.rem('token');
```

### DEF.onPrefLoad = function(next) {}

Type: `delegate`

Loads the preferences at start.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `next` | `Function` | yes |  | `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.

Example: Preferences in a database table
```js
// 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');
};
```

### DEF.onPrefSave = function(data) {}

Type: `delegate`

Saves the preferences.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | yes |  | 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`.

Example: Log every save
```js
var save = DEF.onPrefSave;
DEF.onPrefSave = function(data) {
	console.log('Preferences saved');
	save(data);
};
```

### COUNTER(name)

Type: `method`

Returns a counter that keeps daily statistics.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Count visits
```js
exports.install = function() {
	ROUTE('GET /', index);
};

function index() {
	COUNTER('visits').hit('homepage');
	this.view('index');
}
```

### counter.hit(id, [value])

Type: `method`

Adds a value to the counter of today.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | What you count, for example a page or a product. |
| `value` | `Number` | no | `1` | The value to add. |

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`.

Example: Count an amount
```js
COUNTER('sales').hit('eshop', order.price);
COUNTER('sales').hit('orders');
```

### counter.flush()

Type: `method`

Writes the collected values to the file now.

Returns: `Counter` The counter, for chaining.

The counter calls it periodically. Call it yourself before a planned stop so that no hits are lost.

Example: Flush before exit
```js
ON('exit', function() {
	COUNTER('visits').flush();
});
```

### counter.count([id], [callback])

Type: `method`

Returns the total sum of all stored values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String|Array` | no |  | An id or an array of ids. |
| `callback` | `Function` | no |  | `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.

Example: Total visits
```js
COUNTER('visits').count('homepage', function(err, sum) {
	console.log('Visits:', sum);
});
```

### counter.daily(id, [callback])

Type: `method`

Returns the stored days of one id.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the counter. |
| `callback` | `Function` | no |  | `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.

Example: The last 30 days
```js
COUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {
	console.log(days);
});
```

### counter.monthly(id, [callback])

Type: `method`

Returns the values of one id grouped by month.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the counter. |
| `callback` | `Function` | no |  | `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.

Example: Monthly sales
```js
COUNTER('sales').monthly('eshop', function(err, months) {
	months.forEach(m => console.log(m.year, m.month, m.sum));
});
```

### counter.yearly(id, [callback])

Type: `method`

Returns the values of one id grouped by year.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the counter. |
| `callback` | `Function` | no |  | `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.

Example: Yearly visits
```js
COUNTER('visits').yearly('homepage', console.log);
```

### counter.summarize([type], [callback])

Type: `method`

Returns totals of all ids.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no |  | `'monthly'` or `'yearly'`. |
| `callback` | `Function` | no |  | `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.

Example: Top pages
```js
COUNTER('visits').summarize(function(err, items) {
	items.quicksort('sum_desc');
	console.log(items.slice(0, 10));
});
```

### counter.find()

Type: `method`

Returns a query builder over the stored documents.

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`.

Example: One month of all ids
```js
COUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);
```

### counter.remove([id], [callback])

Type: `method`

Removes stored documents of one id, or all of them.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | no |  | The id of the counter. |
| `callback` | `Function` | no |  | `function(err, count)`. |

Returns: `QueryBuilder` The query builder.

Without `id` every stored document is removed. Values that are not flushed yet stay in memory.

Example: Remove one id
```js
COUNTER('visits').remove('oldpage');
```

### counter.clear()

Type: `method`

Removes all stored data of the counter.

Returns: `Counter` The counter, for chaining.

Empties the file. Values that are not flushed yet stay in memory.

Example: Reset statistics
```js
COUNTER('visits').clear();
```

### INMEMORY(name)

Type: `method`

Returns a NoSQL database that keeps its documents in memory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: A list of online users
```js
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);
```

### TEXTDB(name)

Type: `method`

Returns a NoSQL database stored in several files of a folder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Log of events
```js
TEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });

TEXTDB('events').find().where('type', 'login').take(50).callback(console.log);
```

### BACKUP(filename, path, [callback], [filter])

Type: `method`

Packs the files of a folder into one backup file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | The path of the backup file, or a writable stream. |
| `path` | `String|Array` | yes |  | A folder, or an array of paths relative to the root of the app. |
| `callback` | `Function` | no |  | `function(err, meta)` where `meta` is `{ filename, files, size }`. |
| `filter` | `Function` | no |  | `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.

Example: Back up uploaded files
```js
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');
});
```

### RESTORE(filename, target, [callback], [filter])

Type: `method`

Unpacks a backup file made by BACKUP() into a folder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | The path of the backup file, or a readable stream. |
| `target` | `String` | yes |  | The folder where the files are written. |
| `callback` | `Function` | no |  | `function(err, meta)` where `meta` is `{ files, size, path }`. |
| `filter` | `Function` | no |  | `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.

Example: Restore uploaded files
```js
RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {
	console.log('Restored', meta.files, 'files', meta.size, 'bytes');
});
```
