Utilities
The global helpers of Total.js 5: the U/Utils module, identifiers, copies, the in-memory cache, shared objects, PATH, MEMORIZE(), BACKUP() and RESTORE().
On this page
Total.js 5 puts a set of helpers in the global scope as soon as the framework loads. Most of them come from the Utils module (utils.js), which is also available as the global U. Others are shared objects (MAIN, REPO, FUNC, TEMP), the in-memory CACHE, the PATH functions for the application directories, and a few tools for persistent state and archives (MEMORIZE(), BACKUP(), RESTORE()).
var id = UID(); // 'JacVuE1cn61f'
var copy = CLONE(model); // deep copy
var url = QUERIFY('/api/products/', { page: 2, q: 'shoe' });
var file = PATH.databases('settings.json');
CACHE.set('stats', data, '10 minutes');The full list is in the reference of Utilities. The methods added to String, Number, Date and Array are on the page Prototypes.
Identifiers and hashes
UID() returns a short unique string, made from the time, an internal counter and a random character. It sorts roughly by creation time and is the identifier that Total.js apps use for records. GUID() returns a UUID-like string; GUID(10) returns 10 random characters. HASH() hashes a string: without a type it returns an unsigned 32-bit number, with a type ('md5', 'sha1', 'sha256', 'sha512', 'crc32') it returns that hash.
var model = {};
model.id = UID();
model.token = GUID(30);
model.checksum = HASH(model.id + model.token, 'sha256');For random values, U.random(max, min) returns a number in the range, and U.random_text(n), U.random_string(n) and U.random_number(n) return strings of n characters (letters and digits, letters only, digits only).
Copying and comparing objects
CLONE() makes a deep copy: nested objects and arrays are copied, buffers in object properties are duplicated, dates and errors are kept as they are. COPY() copies the keys of one object into another; with false as the third argument it copies only the keys that the target already has, which is a simple way to update a record with only the fields you allow.
var user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true };
var form = { name: 'Lucia', email: 'lucia@example.com', admin: false };
var allowed = { name: '', email: '' };
COPY(form, allowed, false); // { name: 'Lucia', email: 'lucia@example.com' }
U.extend(user, allowed); // user.admin stays trueDIFFARR() compares two arrays of objects by one property. It tells you what to insert, what to update and what to remove, which is what you need when a form sends the full list of items that belong to a record:
var db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
var form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }];
var diff = DIFFARR('id', db, form);
// diff.add === [{ id: 3, name: 'C' }]
// diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }]
// diff.rem === [1]U.get(obj, 'a.b.c') reads a nested value and returns undefined when a part of the path is missing. U.set(obj, 'a.b.c', value) writes it and creates the missing objects on the way, and arrays for an index (U.set(obj, 'items[0].name', 'Pen') gives { items: [{ name: 'Pen' }] }). U.sortcomparer('name,price_desc') returns a compare function for Array.prototype.sort().
Converting values
U.parseInt(), U.parseFloat() and U.parseBoolean() accept any value (a string from a query string, a number, null) and return a number or a boolean, with a default for empty values:
var page = U.parseInt(this.query.page, 1);
var price = U.parseFloat('12,50'); // 12.5
var active = U.parseBoolean('on'); // trueQUERIFY() builds a query string from an object. It skips null, undefined and empty values, writes dates as ISO strings and joins arrays with commas. It also accepts a URL with an HTTP method in front, as REQUEST() and AJAX() use it:
QUERIFY({ q: 'red shoes', tags: ['a', 'b'] }); // '?q=red%20shoes&tags=a%2Cb'
QUERIFY('GET /api/products/', { page: 2 }); // 'GET /api/products/?page=2'Hostnames
A host name from a user or from the configuration can be written in many ways that resolve to the same server: 127.1, 0x7f.0.0.1 and 2130706433 are all 127.0.0.1, and münchen.de is xn--mnchen-3ya.de. U.validhost(host) accepts only plain ASCII host names and IP addresses in their canonical form. U.tohost(host) converts a host name to that form, or returns an empty string when it is not valid:
U.validhost('example.com'); // true
U.validhost('127.1'); // false
U.tohost('münchen.de'); // 'xn--mnchen-3ya.de'
U.tohost('127.1'); // '127.0.0.1'
U.tohost('a\0b.com'); // ''The framework uses them for its own connections: U.connect() (and so LDAP()) and the SMTP server of the mail convert the host first and give an error for an invalid one, and U.resolve() checks the host before the DNS query.
Shared objects
| Global | What it is for |
|---|---|
MAIN | An empty object for the shared state of your application |
REPO | An empty object for shared data; also available in views |
FUNC | An empty object for your own shared functions |
TEMP | An object for short-lived data; the framework replaces it with an empty object every 5 minutes |
MODS | The loaded modules from /modules/, by their id |
NOW | A Date that the framework refreshes every 5 seconds |
NOOP | An empty function, for callbacks you do not need |
EMPTYOBJECT, EMPTYARRAY | A frozen {} and [], for default values that must not change |
MAIN, REPO, FUNC and MODS can be read in views too. Use NOW where the current second is precise enough (cache keys, expirations, logs); it saves a new Date() in hot code.
// definitions/init.js
FUNC.slug = function(name) {
return name.slug();
};
MAIN.settings = { title: 'My shop' };
// anywhere else
var slug = FUNC.slug('Red shoes');In-memory cache
CACHE keeps values in the memory of the process with an expiration. set() stores a value (5 minutes when you omit the expiration), get() returns it or a default, and remove() and reset() delete items. Expired items are removed every minute.
async function products($) {
var items = CACHE.get('products');
if (!items) {
items = await DATA.find('nosql/products').promise($);
CACHE.set('products', items, '2 minutes');
}
$.callback(items);
}The cache is not shared between threads or cluster instances, and it is empty after a restart. For a result that must survive a restart, see FILECACHE() on the page Caching generated data in a file.
Caching generated data in a file
FILECACHE(id, expire, callback, maker) keeps the result of an expensive task in a file in tmp/, so it survives restarts. The maker runs only when the file is missing or older than expire.
FILECACHE('sitemap', '1 hour', function(err, response) {
console.log(response.length);
}, function(next) {
DATA.find('nosql/pages').fields('id,url').callback(function(err, response) {
next(err, response);
});
});Persistent state with MEMORIZE()
MEMORIZE(name) reads databases/memorize_{name}.json and returns its content as an object. Change the object and call save(), or use set(key, value): the file is written 10 seconds later (a custom delay is the second argument), so many changes in a row produce one write.
var stats = MEMORIZE('stats');
if (!stats.visits)
stats.visits = 0;
function visit() {
stats.visits++;
stats.save();
}Paths
PATH.root(), PATH.public(), PATH.private(), PATH.databases(), PATH.temp(), PATH.logs(), PATH.plugins(), PATH.modules() and the others return the absolute path of an application directory, joined with the relative path you pass. The directory is created the first time you ask for a path inside it.
var filename = PATH.databases('exports/' + UID() + '.csv');
var exists = await PATH.exists(filename);PATH.exists(), PATH.unlink() and PATH.rmdir() cover the common file operations, and U.ls() lists a directory recursively. For the other operations, Total.Fs is the Node.js module node:fs and Total.FsPromises is node:fs/promises:
var text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');Archives with BACKUP() and RESTORE()
BACKUP() packs files and directories into one text file (each file compressed with gzip), and RESTORE() unpacks it into a target directory. Both accept a filter, to leave out paths or (in RESTORE()) to rename them.
await BACKUP(PATH.temp('site.backup'), PATH.public());
await RESTORE(PATH.temp('site.backup'), PATH.root('public-copy'));Large data
U.streamer() returns a function for the data event of a stream and calls you back with each part between two delimiters (or up to a separator), so a large XML or CSV file is processed without loading it whole. U.chunker() stores a long list in temporary files, max items per file, and reads it back page by page. A new chunker with the same name picks up the pages left on disk with chunker.load().
var Fs = require('fs');
var chunker = U.chunker('export', 500);
var stream = Fs.createReadStream(PATH.databases('products.xml'));
stream.on('data', U.streamer('<product>', '</product>', function(value) {
chunker.write(value.parseXML());
}));
stream.on('end', function() {
chunker.end();
chunker.each(function(items, next) {
// 500 products at a time
next();
});
});For the streamed answers of AI chat APIs, U.aistreamer() turns the chunks into lines of text. It reads both the server-sent events of OpenAI completions and the JSON lines of Ollama:
var parser = U.aistreamer(function(line) {
print(line);
});
response.stream.on('data', parser);Promises
Most helpers that take a callback return a promise when you omit it (PATH.exists(), U.ls(), U.wait(), BACKUP(), RESTORE()). For your own callback-style functions, PROMISIFY(fn, a, b, c) calls fn with up to three arguments and a callback, and returns a promise:
var Fs = require('fs');
var buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));