Spanish Total.js
English
Documentation For AI agents
Contents

Utilities

U/Utils functions, global helpers (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), shared objects, CACHE, MEMORIZE, BACKUP, RESTORE and PATH.

.md GitHub
On this page

This page lists the global helpers, the shared global objects, the in-memory CACHE, the PATH functions and the functions of the U (Utils) module that applications use. The guide Utilities explains how they fit together, with examples. The methods added to String, Number, Date and Array are in Prototypes.

API

property

U

The Utils module as a global object.

Returns Object The Utils module.

All functions of utils.js are available through U and its alias Utils (both point to the same object). This page documents the functions that applications use; the others are used by the framework itself.

Use a helper
var ext = U.getExtension('photo.JPG'); // 'jpg'
var same = Utils === U;           // true
method

UID()

Returns a new unique identifier.

Returns String For example JacVuE1cn61f.

The identifier is a short string of letters and digits: a base-62 time stamp (in tenths of a second), an internal counter, a random character chosen at start-up (changed every minute), the length of the time part, a parity digit and the letter f. Identifiers created later sort after earlier ones in most cases. The uid validator of the framework (DEF.validators.uid) accepts them.

A new record
var model = {};
model.id = UID();
model.dtcreated = NOW;
NOSQL('products').insert(model);
method

GUID([length])

Returns a UUID-like string, or a random string of a given length.
ParameterTypeDescription
length? Number The number of characters. Omit it for the UUID-like format.

Returns String

Without length, it returns a string in the shape xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx (36 characters) built from the current time and random hexadecimal digits. With length, it returns that many random characters from 0-9 and a-z.

Tokens
var guid = GUID();       // '1a1e0561-0561-4c86-8eaf-d9a327a65943'
var token = GUID(30);    // 30 random characters
method

HASH(value, [type])

Hashes a string.
ParameterTypeDescription
value String The text to hash.
type? String md5, sha1, sha256, sha512, crc32 or crc32unsigned.

Returns Number|String A number without a type, a hexadecimal string for md5/sha types.

Without type, it returns an unsigned 32-bit number computed from the string (fast, not cryptographic). With a type it returns the hash as a hexadecimal string (md5, sha1, sha256, sha512) or a CRC32 number (crc32, crc32unsigned). value must be a string; convert numbers with + '' first.

Hashes
HASH('abc');            // 96354
HASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'
HASH(email, 'sha256');
method

CLONE(obj, [skip], [nofunctions])

Makes a deep copy of an object or an array.
ParameterTypeDescription
obj Object|Array The value to copy. Other values are returned unchanged.
skip? Object Keys to leave out, e.g. { password: 1 }.
nofunctions? Boolean true leaves out functions. Default: false

Returns Object|Array The copy.

Nested objects and arrays are copied, buffers in object properties are duplicated, and dates, errors and other non-object values are kept as they are. skip is an object whose keys are left out of the copy at every level. With nofunctions, properties that contain functions are left out too.

Copy without a key
var user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } };
var safe = CLONE(user, { password: 1 });
safe.address.city = 'Prague';  // user.address.city is still 'Bratislava'
method

COPY(source, [target], [all])

Copies the keys of one object into another.
ParameterTypeDescription
source Object The object to read.
target? Object The object to write into.
all? Boolean false writes only the keys that target already has. Default: true

Returns Object The target (or the new copy).

Each value of source is cloned and written into target. With all set to false, only keys that are already defined in target are written, so target works as a list of allowed fields. Without target, it returns a deep copy of source.

Allowed fields
var allowed = { name: '', email: '' };
COPY(this.body, allowed, false);
// allowed contains only name and email from the body
method

DIFFARR(prop, db, form)

Compares two arrays of objects by one property.
ParameterTypeDescription
prop String The key that identifies an item, e.g. id.
db Array The current items (for example from the database).
form Array The new items (for example from a form).

Returns Object { add: Array, upd: Array, rem: Array }.

Items are matched when their prop values are equal (==). The result has three arrays: add holds the items of form that are not in db, upd holds pairs { db, form } of matched items, and rem holds the prop values of the db items that are not in form.

Synchronize items
var diff = DIFFARR('id', current, model.items);

for (var item of diff.add)
	NOSQL('items').insert(item);

for (var pair of diff.upd)
	NOSQL('items').modify(pair.form).where('id', pair.db.id);

for (var id of diff.rem)
	NOSQL('items').remove().where('id', id);
method

QUERIFY([url], obj)

Builds a query string from an object.
ParameterTypeDescription
url? String A URL, optionally with a method in front.
obj Object The values.

Returns String

Keys and values are URL-encoded. null, undefined and empty values are skipped, dates are written as ISO strings and arrays are joined with commas. Without url, the result starts with ? (or is an empty string when nothing is left). With url, the query string is appended with ? or &; the URL may start with an HTTP method (GET, POST, PUT, PATCH, DELETE, API) followed by a space, as REQUEST() and AJAX() take it. The function is also U.querify().

Query strings
QUERIFY({ q: 'red shoes', page: 2 });           // '?q=red%20shoes&page=2'
QUERIFY('/api/?lang=en', { page: 2 });         // '/api/?lang=en&page=2'
QUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5'
method

PROMISIFY(fn, [a], [b], [c])

Calls a callback-style function and returns a promise.
ParameterTypeDescription
fn Function A function whose last argument is a callback.
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.

Returns Promise

fn is called with the arguments you pass (up to three) and a callback function(err, response). The promise rejects with err or resolves with response. Pass only the arguments you need: an argument that is undefined ends the list.

Read a file
var Fs = require('fs');
var buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));
method

ERROR([name])

Returns a callback that logs errors.
ParameterTypeDescription
name? String The name shown with the error, e.g. the function that failed.

Returns Function function(err).

The returned function takes err as its first argument and, when it is set, passes it to the error handler of the framework (DEF.onError, which prints it and keeps it in the stats) with name as the source. Use it for callbacks whose result you do not need but whose errors you want to see.

Log a failed write
Fs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save'));
method

print(...values)

Writes values to the console.
ParameterTypeDescription
values Object The values to print.

print is console.log. The framework uses it for its start-up information.

Print
print('Imported', count, 'products');
property

NOW

A Date with the current time, refreshed every 5 seconds.

Returns Date

The framework assigns new Date() to NOW every 5 seconds once it is loaded, and also when it writes an error, an audit log or a cache item. Use it where a precision of a few seconds is enough: expirations, log lines, dtcreated fields. Do not change the object; assign a new date instead.

Expiration
var expire = NOW.add('1 hour');
if (session.expire < NOW)
	delete sessions[session.id];
property

NOOP

An empty function.

Returns Function

Use it where a callback is required but you do not need the result. It is the same function as U.noop.

Ignore the result
Fs.unlink(filename, NOOP);
property

EMPTYOBJECT

A frozen empty object; EMPTYARRAY is a frozen empty array.

Returns Object

EMPTYOBJECT ({}) and EMPTYARRAY ([]) are created once and frozen with Object.freeze(), so they cannot be changed. Use them as default values instead of creating new objects, for example var opt = options || EMPTYOBJECT;. Never write into them: in strict mode a write throws.

Defaults
function find(filter) {
	var opt = filter || EMPTYOBJECT;
	var tags = opt.tags || EMPTYARRAY;
	return tags.length;
}
property

MAIN

A global object for the shared state of the application.

Returns Object

The framework creates MAIN as an empty object and does not use it. Store there what several files of your application share: settings loaded at start, open connections, counters. It is readable in views as MAIN.

Shared settings
// definitions/settings.js
MAIN.settings = MEMORIZE('settings');

// a controller or an action
var title = MAIN.settings.title;
property

REPO

A global object for shared data, also available in views.

Returns Object

An empty object that the framework creates at start (it is also F.repo). Views can read it as REPO, which makes it a good place for data that layouts need, for example a menu or the contact information.

Data for the layout
REPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }];

// views/layout.html
// @{foreach m in REPO.menu}<a href="@{m.url}">@{m.name}</a>@{end}
property

FUNC

A global object for your shared functions.

Returns Object

An empty object for functions that several parts of the application use. Define them in /definitions/ so they exist before the first request. Views can read FUNC too.

A shared function
// definitions/func.js
FUNC.price = function(value) {
	return value.format(2) + ' EUR';
};

// anywhere
var text = FUNC.price(12.5);
property

TEMP

A global object for short-lived data, cleared every 5 minutes.

Returns Object

Every 5 minutes the framework replaces TEMP with a new empty object. Use it for small temporary data that may disappear at any time, such as one-time tokens or throttling counters. Always read it through the global (TEMP.key), not through a saved reference, because the object changes.

A short-lived token
var token = GUID(20);
TEMP[token] = { userid: user.id };

// later
var data = TEMP[token];
if (!data)
	$.invalid('The token has expired');
property

MODS

The loaded modules by their id.

Returns Object

Each .js file in /modules/ is loaded at start and stored in MODS under its exports.id, or under the file name when it does not set one. Its install() function, if any, is called after loading. MODS is the same object as F.modules and can be read in views.

A module
// modules/pricing.js
exports.id = 'pricing';
exports.vat = function(price) {
	return price * 1.2;
};

// anywhere
var total = MODS.pricing.vat(100);
method

CACHE.set(key, value, [expire])

Stores a value in the in-memory cache.
ParameterTypeDescription
key String The key.
value Object Any value.
expire? String How long the value is valid. Default: '5 minutes'

The value is kept in the memory of the process until it expires. expire is a duration in the form that Date.add() accepts ('30 seconds', '5 minutes', '1 hour', '2 days'). The value is stored as it is, not copied: change it and the cached value changes too. Expired items are removed every minute.

Cache a result
CACHE.set('products', items, '2 minutes');
method

CACHE.get(key, [def])

Reads a value from the in-memory cache.
ParameterTypeDescription
key String The key.
def? Object The value returned when the key is missing or expired.

Returns Object

Returns the value when it exists and has not expired; otherwise def. CACHE.read() is an alias.

Read or load
var items = CACHE.get('products');
if (!items) {
	items = await DATA.find('nosql/products').promise($);
	CACHE.set('products', items, '2 minutes');
}
method

CACHE.remove(key)

Removes one value from the in-memory cache.
ParameterTypeDescription
key String The key.

Call it when the cached data changes, so the next read loads fresh data.

Invalidate
NOSQL('products').insert(model).callback(function() {
	CACHE.remove('products');
});
method

CACHE.reset([search])

Removes many values, or all of them.
ParameterTypeDescription
search? String|RegExp A part of the keys, or a pattern.

Returns Number The number of removed keys.

Without search, the whole cache is cleared. With a string, every key that contains it is removed; with a regular expression, every key that matches it. Returns the number of removed keys (0 when the whole cache is cleared).

Remove a group
CACHE.set('products_1', a);
CACHE.set('products_2', b);
CACHE.reset('products_');  // 2
CACHE.reset(/^user_/);
CACHE.reset();             // everything
method

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

Returns an object that is saved to a JSON file.
ParameterTypeDescription
name? String The name of the file.
delay? Number Milliseconds between the last change and the write. Default: 10000
skip? String|Array Keys not written to the file, as an array or a comma-separated string.

Returns Object The data with save() and set(key, value).

Reads databases/memorize_{name}.json (or databases/memorize.json without a name) and returns its content as an object (an empty object when the file does not exist). The object gets two functions: save() schedules a write of the whole object, and set(key, value) assigns a value and calls save(). The write happens delay milliseconds after the last call, so many changes produce one write. skip lists keys that are not written. The arguments delay and skip may be swapped. Call MEMORIZE() once per name and keep the object; every call reads the file again.

Settings that survive restarts
var settings = MEMORIZE('settings', 'cache');

settings.set('title', 'My shop');

settings.counter = (settings.counter || 0) + 1;
settings.cache = {};      // not written
settings.save();
method

BACKUP(filename, files, [callback], [filter])

Packs files and directories into one archive file.
ParameterTypeDescription
filename String|Stream The archive file to create (an existing file is replaced).
files String|Array A directory, or paths relative to the root.
callback? Function function(err, meta).
filter? Function function(path, isdirectory); return true to pack the path.

Returns Promise When callback is omitted.

Writes a text archive: one line per directory and one line per file, with the path and the gzip-compressed content in base64. files is a directory (everything in it is packed with paths relative to it) or an array of paths relative to the application root (files and whole directories). Names that contain .git, .gitignore, .npmignore or .ds_store are skipped. filter(path, isdirectory) gets each path (starting with /) and leaves it out when it returns a falsy value. filename can also be a writable stream. The callback gets { filename, files, size }; without a callback, the function returns a promise.

Back up the uploads
var meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {
	return isdir || !path.endsWith('.tmp');
});
print(meta.files, 'files', meta.size, 'bytes');
Selected paths
await BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);
method

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

Unpacks an archive made by BACKUP().
ParameterTypeDescription
filename String|Stream The archive.
target String The directory to unpack into.
callback? Function function(err, meta).
filter? Function function(path, isdirectory).

Returns Promise When callback is omitted.

Creates the directories and files of the archive inside target. filename can also be a readable stream. filter(path, isdirectory) is called for each item: for a directory, false skips creating it; for a file, return false to skip it, a string to write it under that path (relative to target), or nothing to keep its path. The callback gets { files, size, path }; without a callback, the function returns a promise.

Restore
var meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));
print('Restored', meta.files, 'files');
Skip files on the way
RESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {
	err && print(err);
}, function(path, isdir) {
	if (!isdir && path.startsWith('/config'))
		return false;
});
method

PATH.root([path])

Returns the root directory of the application, or a path inside it.
ParameterTypeDescription
path? String A relative path.

Returns String An absolute path.

The root is the directory of the application (where the start script runs). With path, it returns the root joined with it. Like the other directory functions of PATH, it creates the directory the first time it is called with a path. PATH.public(), PATH.private(), PATH.logs(), PATH.plugins(), PATH.modules(), PATH.templates(), PATH.flowstreams() and PATH.scripts() work the same for their directories.

Paths
PATH.root();                 // '/www/app'
PATH.root('config');         // '/www/app/config'
PATH.private('report.pdf');  // '/www/app/private/report.pdf'
method

PATH.databases([path])

Returns the databases directory, or a path inside it.
ParameterTypeDescription
path? String A relative path.

Returns String An absolute path.

The directory /databases/ holds the files of NoSQL databases, MEMORIZE() files and other data of the application. It is created when you first ask for a path inside it.

A data file
var filename = PATH.databases('import.json');
Fs.writeFile(filename, JSON.stringify(data), NOOP);
method

PATH.temp([path])

Returns the temporary directory, or a path inside it.
ParameterTypeDescription
path? String A relative path.

Returns String An absolute path.

The directory /tmp/ holds uploads, cached files and compiled assets. PATH.tmp() is an alias. When the application starts, the framework deletes its own temporary files there (.js, .css, .html, .htm, .tmp and .upload files). Keep data that must last in /databases/.

A temporary file
var filename = PATH.temp(UID() + '.csv');
method

PATH.exists(path, [callback])

Checks whether a file or a directory exists.
ParameterTypeDescription
path String An absolute path.
callback? Function function(exists, size, isfile).

Returns Promise<Boolean> When callback is omitted.

The callback gets three arguments: exists, the size in bytes and isfile (true for a file, false for a directory). Without a callback, the function returns a promise that resolves with exists.

Check a file
if (await PATH.exists(PATH.databases('settings.json')))
	print('Settings found');

PATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) {
	print(exists, size, isfile);
});
method

PATH.unlink(files, [callback])

Deletes one or more files.
ParameterTypeDescription
files String|Array An absolute path, or an array of paths.
callback? Function function().

Deletes the files one after another and then calls the callback. Errors (for example a missing file) are ignored.

Delete files
PATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() {
	print('Removed');
});
method

PATH.rmdir(directories, [callback])

Deletes directories with everything in them.
ParameterTypeDescription
directories String|Array An absolute path, or an array of paths.
callback? Function function().

For each directory, all files are deleted, then the subdirectories from the deepest one, then the directory itself. Then the callback is called.

Delete a directory
PATH.rmdir(PATH.temp('export'), function() {
	print('Directory removed');
});
property

Total.FsPromises

The Node.js module node:fs/promises.

Returns Object The module node:fs/promises.

The promise version of the file system functions of Node.js, loaded by the framework. F.FsPromises is the same object, and Total.Fs (F.Fs) is the module node:fs.

Read and list
var text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');
var files = await Total.FsPromises.readdir(PATH.public());
method

U.parseInt(value, [def])

Converts any value to a number.
ParameterTypeDescription
value Object The value to convert.
def? Number The result for empty or invalid values. Default: 0

Returns Number

A number is returned as it is. A string is trimmed and converted with the unary +; other values are converted to a string first. null, undefined, an empty string and a value that is not a number return def (0 by default). The result is not rounded ('1.5' gives 1.5). U.parseFloat(value, [def]) works the same and also accepts a comma as the decimal separator ('12,50' gives 12.5).

Query values
var page = U.parseInt(this.query.page, 1);
var price = U.parseFloat(this.query.price);
method

U.parseBoolean(value, [def])

Converts any value to a boolean.
ParameterTypeDescription
value Object The value to convert.
def? Boolean The result for null or undefined. Default: false

Returns Boolean

A boolean is returned as it is; a number is true when it is greater than 0; the strings true, 1 and on (in any case) are true and every other string is false. null and undefined return def (false by default).

A checkbox
var newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true
method

U.get(obj, path)

Reads a nested value by a path.
ParameterTypeDescription
obj Object The object to read.
path String The path.

Returns Object The value, or undefined.

The path uses dots and brackets: a.b.c, items[0].name. When a part of the path is missing, it returns undefined instead of throwing. Paths with spaces, parentheses or keywords such as __proto__ and constructor are refused (undefined). Compiled readers are cached per path.

Nested values
var data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] };
U.get(data, 'user.address.city');  // 'Bratislava'
U.get(data, 'items[0].name');      // 'A'
U.get(data, 'user.phone.number');  // undefined
method

U.set(obj, path, value)

Writes a nested value by a path.
ParameterTypeDescription
obj Object The object to write into.
path String The path.
value Object The value.

Returns Object The written value.

Missing objects on the path are created. A path that ends with [] pushes the value into the array, and an index creates an array with objects in it (items[0].name). Paths with spaces, parentheses or keywords such as __proto__ and constructor are refused: nothing is written. Returns the value.

Build an object
var model = {};
U.set(model, 'address.city', 'Bratislava');
U.set(model, 'tags[]', 'new');
// { address: { city: 'Bratislava' }, tags: ['new'] }
Path with an index
var model = {};
U.set(model, 'items[0].name', 'Pen');
// { items: [{ name: 'Pen' }] }
method

U.extend(target, source, [rewrite])

Copies the keys of source into target.
ParameterTypeDescription
target Object The object to write into.
source Object The object to read.
rewrite? Boolean false keeps existing values. Default: true

Returns Object The target.

Every key of source is cloned into target. With rewrite set to false, keys that already exist in target are not changed, which is how you fill defaults. Returns target.

Defaults
var options = { limit: 50 };
U.extend(options, { limit: 10, sort: 'name' }, false);
// { limit: 50, sort: 'name' }
method

U.sortcomparer(sort)

Returns a compare function for Array.sort().
ParameterTypeDescription
sort String For example name or price_desc,name.

Returns Function function(a, b) for Array.prototype.sort().

sort is a comma-separated list of keys; add _desc for descending order (_asc is the default). Nested keys use dots (address.city). The type of each key is read from the first value that is not empty the first time the expression is used, and is kept for later uses of the same expression: strings are compared with diacritics in mind, numbers, booleans and dates by value.

Sort products
products.sort(U.sortcomparer('price_desc,name'));
method

U.random([max], [min])

Returns a random integer in a range.
ParameterTypeDescription
max? Number The largest value. Default: 100000
min? Number The smallest value. Default: 0

Returns Number

Returns an integer between min and max, both included.

A dice
var dice = U.random(6, 1);
method

U.random_text(length)

Returns a random string of letters and digits.
ParameterTypeDescription
length Number The number of characters.

Returns String

The characters are 0-9, A-Z and a-z. U.random_string(length) uses only letters, and U.random_number(length) only digits (returned as a string that does not start with 0). These values come from Math.random(): do not use them as passwords or security tokens.

Random strings
U.random_text(8);    // 'yb7JVb2a'
U.random_string(6);  // 'HNXkTk'
U.random_number(6);  // '825174'
method

U.convert62(number)

Converts a number to a base-62 string.
ParameterTypeDescription
number Number A non-negative number.

Returns String

The digits are 0-9, A-Z and a-z, in this order. The number is rounded down first. U.from62(value) converts the string back to the number. Use it for short codes made from numeric ids.

Short codes
var code = U.convert62(123456);  // 'W7E'
var id = U.from62(code);         // 123456
method

U.getExtension(filename, [raw])

Returns the extension of a file name.
ParameterTypeDescription
filename String A file name, a path or a URL.
raw? Boolean true keeps the original case. Default: false

Returns String

Returns the part after the last dot, without the dot and in lower case (with raw, in the original case). A query string after ? is ignored. Returns an empty string when the name has no extension.

Extensions
U.getExtension('/img/Photo.JPG');      // 'jpg'
U.getExtension('/files/a.pdf?v=1');    // 'pdf'
U.getExtension('README');              // ''
method

U.getName(path)

Returns the last part of a path.
ParameterTypeDescription
path String A path or a URL.

Returns String

Returns the file name (or the last directory) of a path with / or \\ separators. A trailing separator is ignored.

File names
U.getName('/www/app/public/logo.png');  // 'logo.png'
U.getName('/www/app/public/');          // 'public'
method

U.getContentType(ext)

Returns the MIME type for an extension.
ParameterTypeDescription
ext String An extension, e.g. png or .png.

Returns String

The extension may start with a dot. Unknown extensions return application/octet-stream. U.getExtensionFromContentType(type) does the reverse and returns the first extension with that type (or undefined). The whole table is U.contentTypes.

Content types
U.getContentType('png');                     // 'image/png'
U.getContentType('.json');                   // 'application/json'
U.getExtensionFromContentType('image/png');  // 'png'
method

U.btoa(value)

Encodes text or a buffer to base64.
ParameterTypeDescription
value String|Buffer The data to encode.

Returns String

A buffer is encoded directly; other values are converted to a string and encoded as UTF-8. U.atob(value) decodes base64 back to a UTF-8 string.

Base64
var encoded = U.btoa('Hello');   // 'SGVsbG8='
var text = U.atob(encoded);      // 'Hello'
method

U.validhost(host)

Checks that a host name is plain ASCII and that an IP address is in its canonical form.
ParameterTypeDescription
host String The host name or IP address.

Returns Boolean true for a valid host.

Returns false for a value that is not a string, is empty, or contains a character outside the visible ASCII range (spaces, NUL bytes, letters with accents). A value made only of numbers and dots (or hex numbers) must be a canonical IPv4 address: 127.0.0.1 is valid, 127.1, 0127.0.0.1, 0x7f.0.0.1 and 2130706433 are not. Other ASCII values, including IPv6 addresses, return true; the function does not check the full syntax of a host name. Convert an international name with U.tohost() first.

Check hosts
U.validhost('example.com');     // true
U.validhost('127.0.0.1');       // true
U.validhost('127.1');           // false
U.validhost('0x7f.0.0.1');      // false
U.validhost('münchen.de');      // false
U.validhost('evil.example\0.trusted.example'); // false
method

U.tohost(host)

Converts a host name to its canonical ASCII form.
ParameterTypeDescription
host String The host name or IP address.

Returns String The canonical host, or an empty string.

Converts the host with the URL parser of Node.js: letters become lower case, an international name becomes punycode, and an IPv4 address in another notation becomes the dotted form (a leading 0 means an octal number, 0x a hex number). The result is then checked with U.validhost(). A value that contains : (an IPv6 address) is only checked. Returns an empty string when the host is not valid, so test the result before you use it.

Convert hosts
U.tohost('münchen.de');      // 'xn--mnchen-3ya.de'
U.tohost('EXAMPLE.com');     // 'example.com'
U.tohost('127.1');           // '127.0.0.1'
U.tohost('0x7f.0.0.1');      // '127.0.0.1'
U.tohost('evil.example\0.trusted.example'); // ''
Validate input
function host(value) {
	var host = U.tohost(value);
	if (!host)
		throw new Error('Invalid hostname');
	return host;
}
method

U.wait(validator, [callback], [timeout], [interval])

Waits until a condition is true.
ParameterTypeDescription
validator Function Returns true when the wait is over.
callback? Function function(err, success).
timeout? Number Milliseconds before the wait fails. Default: 5000
interval? Number Milliseconds between checks. Default: 500

Returns Promise When callback is omitted.

validator is called right away and then every interval milliseconds until it returns true; then the callback gets (null, true). When timeout passes first, the callback gets an Error('Timeout'). Without a callback, the function returns a promise that resolves or rejects the same way.

Wait for a connection
await U.wait(() => MAIN.db != null, null, 10000, 200);
print('Database ready');
method

U.resolve(url, callback, [param])

Resolves the host of a URL to IPv4 addresses, with a cache.
ParameterTypeDescription
url String An absolute URL.
callback Function function(err, uri, param, addresses).
param? Any A value passed to the callback.

Parses url, checks its host name with U.validhost() and asks the DNS servers for its IPv4 addresses (dns.resolve4(), so the hosts file is not used). The callback gets (err, uri, param, addresses): uri is the parsed URL with host set to the first address, param is the third argument and addresses the whole list. The addresses are cached for the life of the process; a failed lookup is tried once more before err is passed.

A string that is not a URL gives TypeError: Invalid URL, and a host name that is not valid gives the error Invalid hostname without a DNS query. For http and https URLs the URL parser already converts the host; for other schemes a non-canonical address such as tcp://127.1/ gives Invalid hostname. REQUEST() uses this function with the option resolve: true, and RESTBuilder by default.

Resolve a host
U.resolve('https://example.com/api/', function(err, uri, param, addresses) {
	if (err)
		console.log(err.message || err.code);
	else
		console.log(uri.hostname, addresses);
});
method

U.streamer(beg, [end], callback, [skip], [stream])

Splits a stream of data into parts by delimiters.
ParameterTypeDescription
beg String|Buffer The start of a part, or the separator.
end? String|Buffer The end of a part.
callback Function function(value, index); return false to stop.
skip? Number The number of first parts to ignore. Default: 0
stream? Stream A stream whose end event flushes the rest.

Returns Function function(chunk).

Returns a function that you call with each chunk (a buffer), for example as the data handler of a stream. With beg and end, the callback gets each part that starts with beg and ends with end, both included (for example one <item>...</item> of a large XML file). With beg only, beg is a separator and the callback gets each part up to and including it (for example lines with \n). The callback gets (value, index) with the value as a string; returning false stops the parsing. skip ignores that many first parts. With stream, the remaining data is processed when the stream ends. U.streamer2() takes the same arguments and passes buffers instead of strings.

Read a large XML file
var stream = Fs.createReadStream(PATH.databases('products.xml'));
stream.on('data', U.streamer('<product>', '</product>', function(value, index) {
	var product = value.parseXML();
	print(index, product);
}));
Lines of a CSV file
var stream = Fs.createReadStream(filename);
stream.on('data', U.streamer('\n', function(line, index) {
	var cols = line.trim().split(';');
}, 1, stream));  // skips the header line
method

U.connect(options, [callback])

Opens a TCP or TLS connection.
ParameterTypeDescription
options Object { host, port, secure, tls, timeout } and, with secure, other options of tls.connect().
callback? Function function(err, meta).

Connects to options.host and options.port and calls callback(err, meta) when the connection is open. The host is converted with U.tohost() first, so an international name is sent as punycode and 127.1 as 127.0.0.1; a host that is not valid gives the error Invalid hostname and no connection is made. With secure: true the connection uses TLS from the start and the other options (servername, rejectUnauthorized, ca ...) go to tls.connect(). With tls the connection starts as plain TCP and is upgraded to TLS as soon as it is open: tls: true uses the default options of tls.connect(), an object passes its options (servername, rejectUnauthorized, ca ...). With timeout (in milliseconds) a connection that is not open in time gives the error Timeout.

meta has socket (the Node.js socket), opt (the options with the converted host), write(data), ondata(fn) for the received chunks, and close() (also destroy()). LDAP() connects with this function.

Read the greeting of a server
U.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {
	if (err) {
		console.log(err.message);
		return;
	}
	meta.ondata(function(chunk) {
		console.log(chunk.toString());
		meta.close();
	});
});
Upgrade to TLS
U.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {
	if (!err)
		console.log(meta.socket.encrypted); // true
});
method

U.ls(path, [callback], [filter])

Lists the files and directories of a directory recursively.
ParameterTypeDescription
path String The directory.
callback? Function function(files, directories).
filter? String|RegExp|Function The filter.

Returns Promise { files, directories } when callback is omitted.

The callback gets two arrays of absolute paths: files and directories (directories end with the path separator). filter can be a string (paths that contain it, case-insensitive), a regular expression, or a function (path, isdirectory) that returns true to keep the item; string and regular expression filters apply to files only. A directory that the filter drops is not searched. Without a callback, the function returns a promise with { files, directories }. U.ls2() takes the same arguments and returns files as { filename, stats } objects with the fs.Stats of each file.

Find JSON files
U.ls(PATH.databases(), function(files, directories) {
	print(files);
}, /\.json$/);
Sizes with ls2
var result = await U.ls2(PATH.public('uploads'));
var size = 0;
for (var file of result.files)
	size += file.stats.size;
method

U.chunker(name, [max])

Stores a large list in temporary files, in pages.
ParameterTypeDescription
name String A unique name, used for the file names.
max? Number Items per page. Default: 50

Returns Chunker

A chunker collects items with write(item) (alias append()); every max items are written to a file tmp/{name}-{index}.chunker (compressed with deflate when compress is true, the default) so the memory stays small. Call end() to write the rest. Then each(onitem, [ondone]) reads the pages in order: onitem(items, next, index) gets one page and calls next() to continue, and percentage tells how far the reading is. read(index, callback) reads one page. With autoremove (true by default), each file is deleted after it is read; clear() deletes all files and destroy() also releases the chunker. The properties count and pages hold the number of items and pages.

Process a large export
var chunker = U.chunker('export', 100);

for (var row of rows)
	chunker.write(row);

chunker.end();

chunker.each(function(items, next, index) {
	print('Page', index, chunker.percentage + '%');
	send(items, next);
}, function() {
	print('Done', chunker.count, 'items');
});
method

chunker.load([callback])

since 0.0.16 Finds the pages that an earlier chunker with the same name left on disk.
ParameterTypeDescription
callback? Function function(err, count).

Returns Promise When callback is omitted.

Counts the files of the chunker in the temporary directory and sets the internal page index, so each() and read() can read the pages that an earlier instance wrote and did not read (for example before a restart). Create the chunker with the same name. The callback gets (null, count); without a callback, the function returns a promise that resolves when the counting is done.

Continue a chunker
var chunker = U.chunker('export');
await chunker.load();
chunker.each(function(items, next) {
	send(items, next);
});
class

new U.EventEmitter2() / U.EventEmitter2(obj)

A small event emitter.

Returns EventEmitter2

An object with on(name, fn), once(name, fn), off(name, [fn]) and emit(name, ...args) (up to seven arguments). off(name) without a function removes all handlers of the event. Handlers run with the emitter as this. Called with an object (U.EventEmitter2(obj)), it adds these methods to that object, unless it already has emit, and returns it.

Events on your object
var Cart = {};
U.EventEmitter2(Cart);

Cart.on('add', function(item) {
	print('Added', item.name);
});

Cart.emit('add', { name: 'Shoes' });
method

U.encrypt_data(value, key, [encode])

Obfuscates a string with a key.
ParameterTypeDescription
value String The text.
key String The key.
encode? String The output encoding, or buffer. Default: 'base64'

Returns String|Buffer

Encodes the string with the key and a random 4-byte mask and returns it in base64 (or in the encoding you set; buffer returns a buffer). The same input gives a different output each time. U.decrypt_data(value, key, [encode]) returns the original string, or null for invalid input. This is a light obfuscation, not strong encryption; for sensitive data use ENCRYPT() (see Encryption).

Round trip
var data = U.encrypt_data('hello', 'mykey');
var text = U.decrypt_data(data, 'mykey');  // 'hello'
method

U.encrypt_uid(value, [key])

Signs an identifier so that it cannot be changed.
ParameterTypeDescription
value String|Number The identifier.
key? String The key. Default: CONF.secret

Returns String

Returns the identifier with a checksum in front, made from the value, the key and CONF.secret_uid. U.decrypt_uid(value, [key]) checks it and returns the original identifier (a number when the original was a number) or null when the value was changed. The identifier itself stays readable. Without key, CONF.secret is used.

Signed id in a link
var signed = U.encrypt_uid(123, 'mykey');   // 'n...x123', the checksum depends on CONF.secret_uid
U.decrypt_uid(signed, 'mykey');             // 123
U.decrypt_uid('n2v55u4jx124', 'mykey');     // null
method

U.minify_js(value)

Minifies JavaScript; U.minify_css() and U.minify_html() do the same for CSS and HTML.
ParameterTypeDescription
value String The source code.

Returns String

These are the minifiers that the framework uses for static files and views. They take a string and return the minified string.

Minify
U.minify_js('var a = 1 ;  // note\n');  // 'var a=1;'
U.minify_css('a { color : red ; }');     // 'a{color:red}'
U.minify_html(html);
method

U.aistreamer(online, [onmessage])

since 0.0.16 Parses a streamed response of an AI chat API into lines of text.
ParameterTypeDescription
online Function function(line), called for each complete line of text.
onmessage? Function function(message), called for each parsed JSON message.

Returns Function function(chunk).

Returns a function that you call with each chunk (a buffer) of a streamed response. It reads JSON messages line by line in two formats: server-sent events with data: {...} (OpenAI completions, where the text is in choices[0].delta.content and data: [DONE] ends it) and plain JSON lines (Ollama, where the text is in message.content and done ends it). The text is collected and online(line) is called for every complete line. onmessage(obj), when you set it, gets every parsed message; JSON dates are then parsed as dates.

Print an answer line by line
var parser = U.aistreamer(function(line) {
	print(line);
});

response.stream.on('data', parser);
method

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

Caches the result of a task in a file.
ParameterTypeDescription
id String Identifier of the cached item.
expire String How long the file is valid, for example '5 minutes'.
callback Function function(err, response).
maker Function function(next, id) that creates the value.
encoding? String json or a file encoding such as utf8. Default: json

Looks for the file of id in tmp/. When it exists and is newer than expire, its content goes to callback(err, response). Otherwise maker(next, id) runs; next(err, response, [load]) writes the response to the file and calls callback, unless load is false. With the json encoding the value is stored as JSON and parsed back; any other encoding stores and reads the raw content.

Cache a remote list
FILECACHE('currencies', '1 day', function(err, response) {
	MAIN.currencies = response;
}, function(next) {
	REQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) {
		next(err, err ? null : response.body.parseJSON());
	}});
});
Made in Europe