Spanish Total.js
English
Documentation For AI agents
Contents

Utilities

The functions of U (utils.js) and the global helpers and objects of the framework.

.md GitHub
On this page

Total.js defines helpers in the global scope and in the object U (Utils), so every file of an app can use them without require(). The guide Utilities explains how to use them with examples; this page is the exact reference.

API

property

U

The utility library of the framework (utils.js).

Returns Object

U, Utils and utils are the same object. It is global, so you use it in controllers, schemas, modules and plugins without require().

Use a helper
var ext = U.getExtension('photo.JPG'); // 'jpg'
property

Total

since 0.0.96 A global alias of the framework instance F.

Returns Framework

Total, F and framework refer to the same object.

Same object
console.log(Total === F); // true
property

NOW

A Date that the framework refreshes regularly.

Returns Date

Reading NOW is cheaper than new Date(). The framework sets it again in its internal intervals (about every minute) and in some calls, such as LOGGER(). Use it where a precision of a minute is enough; use new Date() for an exact time. F.datetime reads and writes the same value.

Timestamp of a record
var model = { id: UID(), dtcreated: NOW };
property

EMPTYOBJECT

A frozen empty object.

Returns Object

Use it as a default value that is never modified. It is frozen, so assignments to it have no effect.

Default options
function send(options) {
	options = options || EMPTYOBJECT;
	return options.timeout || 5000;
}
property

EMPTYARRAY

A frozen empty array.

Returns Array

Use it as a default value that is never modified. It is frozen, so push() throws an error.

Default list
var items = response.items || EMPTYARRAY;
method

NOOP()

An empty function.

Returns undefined

Pass it where a callback is required and you do not need the result.

Ignore a callback
Fs.unlink(PATH.temp('export.csv'), NOOP);
property

MAIN

An empty global object for your own shared data.

Returns Object

The framework creates MAIN = {} and does not use it. Store application-wide values in it, for example data loaded at start.

Shared settings
// definitions/init.js
MAIN.settings = { currency: 'EUR' };

// any other file
var currency = MAIN.settings.currency;
property

REPO

An empty global object for your own repository of values.

Returns Object

The framework creates REPO = {} and does not use it. It is a second namespace like MAIN.

Cache a list
REPO.countries = ['SK', 'CZ', 'AT'];
property

FUNC

An empty global object for your own shared functions.

Returns Object

The framework creates FUNC = {}. Put helpers there that several files of the app call.

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

// a controller or a schema
var text = FUNC.price(12.5);
property

TEMP

A global object for temporary data that the framework clears.

Returns Object

The framework replaces TEMP with a new empty object in its periodic cleanup (every CONF.default_interval_clear_cache minutes, 10 by default). Do not keep anything there that you need later.

Short-lived value
if (!TEMP.stats)
	TEMP.stats = compute();
property

MODS

All loaded modules by their name.

Returns Object

The same object as F.modules. A key is the name of the file in /modules/ (or the id the module exports).

List modules
Object.keys(MODS).forEach(function(name) {
	console.log(name);
});
method

MODULE(name)

Returns a loaded module.
ParameterTypeDescription
name String Name of the module.

Returns Object The module, or null.

Reads F.modules[name]. The result is the exports of the module file, or null when no module of that name is loaded.

Call a module
// modules/mailer.js
exports.send = function(email) { /* ... */ };

// anywhere
MODULE('mailer').send('info@example.com');
method

LOGGER(name, value1, [value2], [...])

Appends a line to a log file in the /logs/ directory.
ParameterTypeDescription
name String Name of the log file without .log.
value Object One or more values to write.

Returns undefined

The line is yyyy-MM-dd HH:mm:ss | values in the file {name}.log. Values are separated by a space; objects are formatted with util.inspect(). The directory is created when it does not exist, and writes go through U.queue() with at most 5 writes at the same time.

Log a payment
LOGGER('payments', 'order', order.id, 'paid', order.price);
// logs/payments.log:
// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9
method

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

since 0.0.97 Calls a callback-style function and returns a Promise.
ParameterTypeDescription
fn Function A function that takes a callback as its last argument.
a? Object First argument.
b? Object Second argument.
c? Object Third argument.

Returns Promise

fn is called with the given arguments and a callback function(err, response) as the last argument. The Promise rejects with err or resolves with response. Up to three arguments are supported; arguments that are undefined are not passed.

Read a file
var Fs = require('fs');
var content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');
Your own function
function load(id, callback) {
	callback(null, { id: id });
}

var item = await PROMISIFY(load, '123');
method

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 Maximum time in ms. Default: 5000
interval? Number Time between checks in ms. Default: 500

Returns undefined

validator() is checked at once and then every interval ms. When it returns true, callback(null, true) is called. When timeout ms pass first, callback(Error('Timeout'), false) is called.

Wait for a connection
WAIT(function() {
	return MAIN.db != null;
}, function(err) {
	if (err)
		console.log('Database is not ready');
	else
		console.log('Ready');
}, 10000);
method

UID([type], [date])

Creates a short unique identifier.
ParameterTypeDescription
type? String A name of an independent counter.
date? Date The time encoded in the ID. Default: NOW

Returns String

The ID is a time-based string, for example 24j0y001xn51d, which sorts by the time it was created. It is unique within the running instance (the framework adds a random instance key). type keeps a separate counter for each type, so IDs of different collections do not share a sequence. date creates the ID for another time. CONF.default_uid selects the version: r gives a random ID (UIDR()), f a base-62 variant; the default is the d version.

A new record
var model = {};
model.id = UID();
model.dtcreated = NOW;
Counter per type
var orderid = UID('orders');
var invoiceid = UID('invoices');
method

UID16([type], [date])

Creates a unique identifier with the time part in base 16.
ParameterTypeDescription
type? String A name of an independent counter.
date? Date The time encoded in the ID. Default: NOW

Returns String

Works like UID() but encodes the time in hexadecimal, so the ID is a little longer (version c). It ignores CONF.default_uid.

Hex-based ID
var id = UID16(); // e.g. '367b52002xn60c'
method

GUID([length])

Creates a GUID or a random string of a given length.
ParameterTypeDescription
length? Number Length of a random string.

Returns String

Without length it returns a string in the UUID form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx built from the current time and random numbers. With length it returns random lowercase letters and digits of that length. Also available as U.GUID().

UUID form
var id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'
Random token
var token = GUID(30);
method

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

Creates a deep copy of an object or an array.
ParameterTypeDescription
obj Object The object or array to copy.
skip? Object Keys to leave out, as { key: true }.
skipFunctions? Boolean Leaves out functions. Default: false

Returns Object A new object.

Nested objects and arrays are copied; Date and Error values are kept by reference, and Buffers are copied. skip is an object of keys to leave out ({ password: 1 }) on the first level of objects. Also available as U.clone().

Copy without a key
var copy = CLONE(user, { password: 1 });
copy.name = 'Peter'; // user.name is unchanged
method

COPY(source, [target])

Copies all properties of source to target.
ParameterTypeDescription
source Object Object to read.
target? Object Object to write.

Returns Object The target.

Every key of source is cloned into target, also keys that target does not have. Without target it returns a new copy of source. It is U.copy(source, target, true).

Merge
var target = { a: 0 };
COPY({ a: 1, z: 9 }, target);
// target: { a: 1, z: 9 }
method

HASH(value, [type])

Creates a hash of a string.
ParameterTypeDescription
value String The text.
type? String A hash algorithm.

Returns Number|String

Without type it returns a fast numeric hash (unsigned 32-bit). type can be md5, sha1, sha256, sha512, crc32 or crc32unsigned. It calls value.hash().

Numeric and MD5
HASH('abc');        // 96354
HASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'
method

QUERIFY([url], obj)

Adds an object to a URL as a query string.
ParameterTypeDescription
url? String The URL.
obj Object Values of the query string.

Returns String

Values that are null or undefined are left out; dates become ISO strings and arrays are joined with commas. Keys and values are encoded. The URL can start with a method (GET /api/); the query is added to the path. Without a URL it returns only ?key=value.

Build a URL
QUERIFY('GET /api/products/', { page: 2, q: 'a b' });
// 'GET /api/products/?page=2&q=a%20b'

QUERIFY({ page: 1 }); // '?page=1'
method

DIFFARR(prop, db, form)

Compares two arrays of objects by a key.
ParameterTypeDescription
prop String Name of the key, for example id.
db Object[] The stored items.
form Object[] The new items.

Returns Object { add: [], upd: [], rem: [] }

Returns { add, upd, rem }: add holds items of form that are not in db, upd holds { db, form } pairs that exist in both, and rem holds the key values of items of db that are missing in form. Use it to save a list that a user edited.

Sync a list
var diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);
// diff.add: [{ id: 3 }]
// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]
// diff.rem: [1]
method

PATH.root([filename])

Returns a path in the root directory of the app.
ParameterTypeDescription
filename? String A relative path.

Returns String

The result always uses / as the separator.

A file in the root
var filename = PATH.root('data/countries.json');
method

PATH.temp([filename])

Returns a path in the temporary directory and creates the directory.
ParameterTypeDescription
filename? String A file name.

Returns String

The directory is CONF.directory_temp. PATH.tmp() and PATH.temporary() are aliases.

Temporary file
var filename = PATH.temp('export-' + UID() + '.csv');
method

PATH.databases([filename])

Returns a path in the databases directory and creates the directory.
ParameterTypeDescription
filename? String A file name.

Returns String

The directory is CONF.directory_databases.

A data file
var filename = PATH.databases('settings.json');
method

PATH.logs([filename])

Returns a path in the logs directory and creates the directory.
ParameterTypeDescription
filename? String A file name.

Returns String

The directory is CONF.directory_logs. LOGGER() writes there.

Read a log
require('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {
	console.log(text);
});
method

PATH.mkdir(path, [cache])

Creates a directory with all missing parent directories.
ParameterTypeDescription
path String An absolute path.
cache? Boolean Skips paths created before. Default: false

Returns undefined

It works synchronously. With cache set to true, a path that was already created is not checked again until the framework clears its cache.

Directory for uploads
var dir = PATH.databases('uploads/2021/');
PATH.mkdir(dir, true);
method

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

Returns a random integer between min and max, both included.
ParameterTypeDescription
max? Number The highest value. Default: 100000
min? Number The lowest value. Default: 0

Returns Number

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

U.random_text(length)

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

Returns String

Characters are 0-9, A-Z and a-z.

A code
var code = U.random_text(8); // e.g. '1qrWGUa7'
method

U.random_string(length)

Returns a random string of letters.
ParameterTypeDescription
length Number Number of characters.

Returns String

Characters are A-Z and a-z, without digits.

Letters only
var name = U.random_string(6);
method

U.random_number(length)

Returns a string of random digits.
ParameterTypeDescription
length Number Number of digits.

Returns String

The first digit is never 0, so +value has the same number of digits. The result is a string.

A PIN
var pin = U.random_number(6); // e.g. '986081'
method

U.encrypt_uid(value, [key])

Signs an ID so that it cannot be changed by the client.
ParameterTypeDescription
value String|Number The ID.
key? String A secret key. Default: CONF.secret

Returns String

The result contains the ID and a checksum of the ID and the key, for example n3ck9tg6x123. The value is not hidden; it is protected against changes. Use U.decrypt_uid() to read it back.

Link with a signed ID
var link = '/download/' + U.encrypt_uid(file.id) + '/';
method

U.decrypt_uid(value, [key])

Reads an ID signed by U.encrypt_uid().
ParameterTypeDescription
value String The signed ID.
key? String The secret key used to sign it. Default: CONF.secret

Returns String|Number The ID, or null.

Returns the original ID (a number when a number was signed), or null when the checksum does not match.

Verify an ID from a URL
var id = U.decrypt_uid(this.params.id);
if (id == null) {
	this.throw404();
	return;
}
method

U.copy(source, [target])

Copies the values of source to the keys that target already has.
ParameterTypeDescription
source Object Object to read.
target? Object Object to write.

Returns Object The target.

Only keys that exist in target (with a value other than undefined) are written; values are cloned. Without target it returns a new copy of source. To copy all keys, use COPY().

Update known fields
var item = { name: '', price: 0 };
U.copy({ name: 'Book', price: 9, hack: true }, item);
// item: { name: 'Book', price: 9 }
method

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

Adds the properties of source to target.
ParameterTypeDescription
target Object Object to write.
source Object Object to read.
rewrite? Boolean Overwrites existing values. Default: true

Returns Object The target.

Values are cloned. With rewrite set to false, keys that already have a value in target are kept, so source acts as a set of defaults.

Defaults
var options = { timeout: 1000 };
U.extend(options, { timeout: 5000, retry: 3 }, false);
// options: { timeout: 1000, retry: 3 }
method

U.reduce(source, props, [reverse])

Keeps only some properties of an object.
ParameterTypeDescription
source Object|Object[] The object or array of objects.
props String[]|Object Keys to keep.
reverse? Boolean Removes the listed keys instead. Default: false

Returns Object|Object[]

props is an array of keys or an object whose keys are used. With reverse set to true, the listed keys are removed instead. An array as source reduces each item. The result is a new object.

Public fields
var output = U.reduce(user, ['id', 'name']);
var safe = U.reduce(user, ['password'], true);
method

U.get(obj, path)

Reads a value by a path such as address.city.
ParameterTypeDescription
obj Object The object.
path String The path with dots.

Returns Object The value.

Returns undefined when a part of the path does not exist. Indexes are written as items[0].name. Paths that contain code-like characters (spaces, brackets of calls, __proto__ and similar) return undefined.

Nested value
U.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'
U.get({}, 'address.city'); // undefined
method

U.set(obj, path, value)

Writes a value by a path such as address.city.
ParameterTypeDescription
obj Object The object.
path String The path with dots.
value Object The value.

Returns Object The value.

Missing objects on the path are created. A path that ends with [] pushes the value to an array. Paths that contain code-like characters are ignored.

Build an object
var obj = {};
U.set(obj, 'address.city', 'Bratislava');
U.set(obj, 'tags[]', 'new');
// { address: { city: 'Bratislava' }, tags: ['new'] }
method

U.trim(obj, [clean])

Trims all string values of an object or an array.
ParameterTypeDescription
obj Object|Array|String The value to trim.
clean? Boolean Replaces empty strings with undefined. Default: false

Returns Object The same value.

Nested objects and arrays are trimmed too; the object is changed in place. With clean set to true, empty strings become undefined.

Clean a form
U.trim({ name: ' Peter ', note: '  ' }, true);
// { name: 'Peter', note: undefined }
method

U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])

Extracts keywords from a text.
ParameterTypeDescription
content String|String[] The text.
forSearch? Boolean Normalizes the words for search. Default: true
alternative? Boolean Shortens the words. Default: false
max_count? Number Maximum number of words read. Default: 200
max_length? Number Longer words are skipped. Default: 20
min_length? Number Shorter words are skipped. Default: 2

Returns String[]

The text is lowercased and split into words; the result is a list of unique words, the most frequent first. With forSearch (the default), diacritics are removed and y is replaced with i, so the same words match in a search. alternative shortens each word to 80 % of its length to match word forms. content can be an array of texts.

Search index
var keywords = U.keywords(product.name + ' ' + product.description).join(' ');
method

U.queue(name, max, fn, [param])

Runs functions with a limit of how many run at the same time.
ParameterTypeDescription
name String Name of the queue.
max Number Maximum running functions.
fn Function function(next, param).
param? Object A value passed to fn.

Returns Boolean

Each call adds fn(next, param) to the queue name. At most max functions of that queue run at once; each must call next() when it finishes. Returns true when fn starts at once, false when it waits.

Three downloads at once
urls.forEach(function(url) {
	U.queue('downloads', 3, function(next, url) {
		download(url, next);
	}, url);
});
method

U.sortcomparer(sort)

Creates a compare function for Array.sort() from a text.
ParameterTypeDescription
sort String The sort definition.

Returns Function function(a, b)

sort is a list of fields separated by commas, each with an optional _asc or _desc suffix, for example price_desc,name. Nested fields such as address.city are supported. Strings, numbers, booleans and dates are compared by their type.

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

U.combine(path1, [path2], [...])

Joins paths relative to the root directory of the app.
ParameterTypeDescription
path String One or more parts of the path.

Returns String An absolute path.

A part that starts with ~ is an absolute path and replaces what was before it. On Windows the result uses /.

Paths in the app
U.combine('/public/', 'img'); // '/www/app/public/img'
U.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'
method

U.join(path1, [path2], [...])

Joins parts of a path with /.
ParameterTypeDescription
path String One or more parts.

Returns String

Slashes at the start and the end of each part are removed, and the result starts with /. Empty parts are skipped.

Join
U.join('a', '/b/', 'c'); // '/a/b/c'
method

U.getExtension(filename, [raw])

Returns the extension of a file name without the dot.
ParameterTypeDescription
filename String The file name or URL.
raw? Boolean Keeps the original case. Default: false

Returns String

The extension is lowercased unless raw is true. A query string after ? is ignored. Returns an empty string when there is no extension.

Extension
U.getExtension('Photo.JPG?width=200'); // 'jpg'
method

U.getName(path)

Returns the last part of a path.
ParameterTypeDescription
path String The path.

Returns String

Works with / and \ separators; a trailing separator is ignored.

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

U.getContentType(ext)

Returns the content type (MIME type) for an extension.
ParameterTypeDescription
ext String The extension.

Returns String

The extension can start with a dot. An unknown extension gives application/octet-stream.

MIME type
U.getContentType('json'); // 'application/json'
U.getContentType(U.getExtension(filename));
method

U.setContentType(ext, type)

Registers or changes the content type of an extension.
ParameterTypeDescription
ext String The extension, with or without a dot.
type String The content type.

Returns Boolean true

The framework uses the table to serve static files, so a new extension also becomes a known static file.

A new extension
// definitions/init.js
U.setContentType('gpx', 'application/gpx+xml');
method

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

Lists all files and directories in a directory and its subdirectories.
ParameterTypeDescription
path String The directory.
callback? Function function(files, directories).
filter? String|RegExp|Function A filter.
unified? Boolean Uses / on Windows. Default: false

Returns Promise|undefined A Promise without a callback.

callback(files, directories) receives arrays of absolute paths. Without a callback the method returns a Promise of { files, directories }. filter is a string (part of the name, not case-sensitive), a RegExp, or function(path, isDirectory) that returns true to keep an item; the string and RegExp filters apply to files only. With unified set to true, paths on Windows use /.

Callback
U.ls(PATH.public(), function(files, directories) {
	console.log(files.length, directories.length);
}, /\.(jpg|png)$/);
Promise
var response = await U.ls(PATH.databases(), 'backup');
console.log(response.files);
method

U.ls2(path, [callback], [filter], [unified])

Lists files with their stats.
ParameterTypeDescription
path String The directory.
callback? Function function(files, directories).
filter? String|RegExp|Function A filter.
unified? Boolean Uses / on Windows. Default: false

Returns Promise|undefined A Promise without a callback.

Works like U.ls(), but each file is { filename, stats }, where stats is the fs.Stats object (size, dates). Directories are still paths.

Total size
U.ls2(PATH.temp(), function(files) {
	var size = 0;
	for (var file of files)
		size += file.stats.size;
	console.log(size.filesize());
});
method

U.encode(value)

Encodes HTML special characters.
ParameterTypeDescription
value Object The value.

Returns String

null and undefined give an empty string; other values are converted to a string first. It calls String.encode().

Safe HTML
U.encode('<b>'); // '&lt;b&gt;'
method

U.decode(value)

Decodes HTML entities back to characters.
ParameterTypeDescription
value Object The value.

Returns String

The opposite of U.encode(). null and undefined give an empty string.

Plain text
U.decode('&lt;b&gt;'); // '<b>'
method

U.btoa(value)

Encodes a string or a Buffer to Base64.
ParameterTypeDescription
value String|Buffer The value.

Returns String

U.atob(value) decodes Base64 back to a UTF-8 string.

Base64
var encoded = U.btoa('hi'); // 'aGk='
var text = U.atob(encoded); // 'hi'
method

U.parseXML(xml, [replace])

Parses XML into a flat object.
ParameterTypeDescription
xml String The XML.
replace? Boolean Replaces special characters in keys. Default: false

Returns Object

Each key is the path of an element joined with dots, for example root.item; repeated elements give an array of values. Attributes are stored under the key with [], for example root.item[]. With replace set to true, the characters [, ], :, . and _ in keys become _. CDATA is read as text.

Read XML
var obj = U.parseXML('<root><item id="1">A</item><item>B</item></root>');
// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }
method

U.parseInt(value, [def])

Converts any value to an integer.
ParameterTypeDescription
value Object The value.
def? Number Value for empty or invalid input. Default: 0

Returns Number

null, undefined and an empty string give def. A number is returned as it is. U.parseFloat(value, [def]) and U.parseBoolean(value, [def]) work the same way for decimals and booleans (def is false for booleans; a number is true when it is greater than 0).

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

U.distance(lat1, lon1, lat2, lon2)

Returns the distance between two GPS coordinates in kilometres.
ParameterTypeDescription
lat1 Number Latitude of the first point.
lon1 Number Longitude of the first point.
lat2 Number Latitude of the second point.
lon2 Number Longitude of the second point.

Returns Number Kilometres.

Uses the haversine formula on a sphere with a radius of 6371 km; the result has at most 3 decimal places.

Bratislava to Prague
U.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225
method

U.minify_css(value)

Minifies CSS with the built-in compiler.
ParameterTypeDescription
value String CSS code.

Returns String

The same compiler the framework uses for static .css files.

Minify
U.minify_css('a { color: red; }'); // 'a{color:red}'
method

U.minify_js(value)

Minifies JavaScript with the built-in compiler.
ParameterTypeDescription
value String JavaScript code.

Returns String

Removes comments and white space. The same compiler the framework uses for static .js files.

Minify
U.minify_js('var a = 1;  // note');
method

U.minify_html(value)

Minifies HTML with the built-in compiler.
ParameterTypeDescription
value String HTML code.

Returns String

Removes white space between tags.

Minify
U.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'
method

STATUS(id, data, [timeout])

since 0.0.63 Stores a named status of your app and passes it to DEF.onStatus(meta).
ParameterTypeDescription
id String|Object The name of the status, or a $ object.
data Object Any value.
timeout? Number Delays the update and merges calls in this time, in milliseconds.

Returns undefined Nothing.

Each id has one status object { id, data, date }. STATUS() replaces its data, sets date and calls DEF.onStatus(meta) when you define it. Instead of an id you can pass a $ object; its ID (or name) is the id.

With timeout (in milliseconds), the update is delayed: the first call starts the timer, later calls only change data, and DEF.onStatus() runs once with the last data when the timer ends. Use it for values that change often, like a progress.

With CONF.allow_stats_status (default true), all statuses are added as status to the stats snapshot that Total.js writes to <main script>.json (CONF.allow_stats_snapshot).

Progress of an import
DEF.onStatus = function(meta) {
	console.log(meta.id, meta.data, meta.date);
};

for (var i = 0; i < items.length; i++)
	STATUS('import', { done: i + 1, total: items.length }, 1000);
method

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

Encrypts a string with a key and a random mask.
ParameterTypeDescription
value String The text to encrypt.
key String The key.
encode? String A Buffer encoding or buffer. Default: base64

Returns String|Buffer The encrypted value.

The output changes on every call because of a random 4-byte mask. encode is a Buffer encoding (default base64); buffer returns the raw Buffer. Read it back with U.decrypt_data() and the same key. This is light obfuscation, not a replacement for U.encrypt_crypto().

Encrypt a JSON string
var token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);
method

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

Decrypts a value made by U.encrypt_data().
ParameterTypeDescription
value String|Buffer The encrypted value.
key String The key used for encryption.
encode? String The encoding of value. Default: base64

Returns String The decrypted text or null.

value is a string in the encode encoding (default base64) or a Buffer. Returns null when the value cannot be read. A wrong key gives a wrong string, not null, so check the result (for example with parseJSON()).

Decrypt a token
var data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();
if (!data)
	return $.invalid(401);
method

U.encrypt_crypto(type, key, value)

Encrypts data with a Node.js cipher.
ParameterTypeDescription
type String A cipher name, for example aes-256-cbc.
key String The key.
value String|Buffer The data.

Returns Buffer The encrypted data.

Uses Crypto.createCipheriv(type, key, CONF.default_crypto_iv). The key length must fit the cipher (32 characters for aes-256-cbc). CONF.default_crypto_iv is created from the app by default, so set it in the config when other apps must decrypt the data.

AES
var key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';
var buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');
var text = buffer.toString('base64');
method

U.decrypt_crypto(type, key, value)

Decrypts data made by U.encrypt_crypto().
ParameterTypeDescription
type String The cipher name.
key String The key.
value Buffer The encrypted data.

Returns Buffer The decrypted data or undefined.

Uses Crypto.createDecipheriv(type, key, CONF.default_crypto_iv). Returns undefined when the data cannot be decrypted.

AES
var buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));
buffer && console.log(buffer.toString('utf8'));
method

U.convert62(number)

since 0.0.85 Converts a number to a base-62 string.
ParameterTypeDescription
number Number A positive number.

Returns String

The alphabet is digits, then upper-case and lower-case letters. Decimals are floored. Read it back with U.from62().

Short code
U.convert62(123456789); // '8M0kX'
method

U.from62(value)

since 0.0.85 Converts a base-62 string from U.convert62() back to a number.
ParameterTypeDescription
value String A base-62 string.

Returns Number

Back to a number
U.from62(U.convert62(1000)); // 1000
method

U.groupify(id, [count])

since 0.0.88 Returns a fixed-length numeric group for an identifier.
ParameterTypeDescription
id String An identifier.
count? Number The number of digits. Default: 4

Returns String A string of digits.

The value is HASH(id, true) modulo 10^count, padded with zeros to count digits. The same id always gives the same group, so it is useful for spreading files into sub-directories.

Sub-directories
var id = UID();
var filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');
method

U.parseBoolean(value, [def])

Converts any value to a boolean.
ParameterTypeDescription
value Object A value.
def? Boolean The default value. Default: false

Returns Boolean

A boolean is returned as it is, a number is true when greater than 0, other values are converted to a string and parsed with String.parseBoolean(). null and undefined return def.

Query value
var active = U.parseBoolean($.query.active);
method

U.parseFloat(value, [def])

Converts any value to a decimal number.
ParameterTypeDescription
value Object A value.
def? Number The default value. Default: 0

Returns Number

A number is returned as it is, other values are converted to a string and parsed with String.parseFloat(). null, undefined and an empty string return def.

Price
var price = U.parseFloat(model.price, 0);
method

U.isDate(value)

Checks that a value is a valid Date.
ParameterTypeDescription
value Object A value.

Returns Boolean

Returns false for an invalid date such as new Date('abc').

Validate a date
U.isDate(new Date()); // true
U.isDate(new Date('abc')); // false
U.isDate('2024-01-01'); // false
property

U.DAYS

English names of the days of the week.

Returns String Array

The array starts with Sunday, so it matches Date.getDay().

Day name
var name = U.DAYS[new Date().getDay()];
property

U.MONTHS

English names of the months.

Returns String Array

The array starts with January, so it matches Date.getMonth().

Month name
var name = U.MONTHS[new Date().getMonth()];
method

U.httpstatus(code, [addCode])

Returns the text of an HTTP status code.
ParameterTypeDescription
code Number An HTTP status code.
addCode? Boolean Adds the code to the text. Default: true

Returns String

The text comes from http.STATUS_CODES. With addCode (default true) the code is added in front.

Status text
U.httpstatus(404); // '404: Not Found'
U.httpstatus(404, false); // 'Not Found'
method

U.toURLEncode(obj)

Serializes an object into a URL-encoded query string.
ParameterTypeDescription
obj Object An object.

Returns String For example q=total&page=2.

Strings are encoded with encodeURIComponent(), numbers and booleans are added as they are, arrays are joined with ,. null, undefined, empty strings and other objects (including dates) are skipped. Returns an empty string when nothing is added.

Query string
var url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });
// q=total%20js&page=2&tags=a%2Cb
method

U.atob(value)

Decodes a base64 string to a UTF-8 string.
ParameterTypeDescription
value String A base64 string.

Returns String

The reverse of U.btoa().

Decode
U.atob(U.btoa('Hello')); // 'Hello'
method

U.isrelative(url)

Checks that a URL is relative.
ParameterTypeDescription
url String A URL.

Returns Boolean

Returns false when the URL starts with // or contains http:// or https://.

Safe redirect
var url = $.query.redirect || '/';
if (!U.isrelative(url))
	url = '/';
$.redirect(url);
method

U.isStaticFile(url)

Checks that a URL looks like a file.
ParameterTypeDescription
url String A URL path.

Returns Boolean

Returns true when the last 8 characters of the URL contain a dot, for example /img/logo.png.

File or route
U.isStaticFile('/img/logo.png'); // true
U.isStaticFile('/api/users/'); // false
method

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

Resolves the IPv4 address of a URL and caches it.
ParameterTypeDescription
url String A URL.
callback? Function function(err, uri, param, addresses).
param? Object A value passed to the callback.

Returns Array|undefined The cached addresses when no callback is given.

callback(err, uri, param, addresses) receives the parsed URL with uri.host replaced by the first address. The addresses are cached per host; without a callback the method returns the cached addresses (or undefined). A failed lookup is tried once more. The clear_dnscache command clears the cache.

DNS lookup
U.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {
	console.log(err, addresses);
});
method

U.link(path1, [path2], [...])

since 0.0.39 Joins URL parts with exactly one / between them.
ParameterTypeDescription
path String One or more URL parts.

Returns String

Unlike U.join(), it does not add a leading / and keeps the parts as they are.

Build a URL
U.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'
method

U.normalize(path)

since 0.0.39 Adds / to the start and the end of a path when it is missing.
ParameterTypeDescription
path String A path.

Returns String

Normalize
U.normalize('admin'); // '/admin/'
method

U.path(path, [delimiter])

Adds a trailing delimiter to a path when it is missing.
ParameterTypeDescription
path String A path.
delimiter? String The delimiter. Default: /

Returns String

An empty path returns the delimiter.

Directory path
U.path('/www/app'); // '/www/app/'
method

U.getExtensionFromContentType(contentType)

since 0.0.63 Returns the file extension of a content type.
ParameterTypeDescription
contentType String A content type.

Returns String

Searches the content types known to U.getContentType() (including the ones added with U.setContentType()). Returns the first match without a dot, or undefined.

Extension
U.getExtensionFromContentType('image/png'); // 'png'
method

U.ObjectToArray(obj)

Converts an object into an array of { key, value } items.
ParameterTypeDescription
obj Object An object.

Returns Array

null or undefined returns EMPTYARRAY.

Key-value list
U.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]
method

U.createBuffer([value], [encoding])

Shortcut for Buffer.from(value || '', encoding).
ParameterTypeDescription
value? String|Array|Buffer The data. Default: ''
encoding? String The encoding of a string. Default: utf8

Returns Buffer

From base64
var buffer = U.createBuffer(body, 'base64');
method

U.createBufferSize([size])

Shortcut for Buffer.alloc(size || 0).
ParameterTypeDescription
size? Number The size in bytes. Default: 0

Returns Buffer A buffer filled with zeros.

Empty buffer
var buffer = U.createBufferSize(4);
buffer.writeInt32BE(100);
method

U.json2replacer(key, value)

A JSON.stringify() replacer that removes null and undefined values.
ParameterTypeDescription
key String The key.
value Object The value.

Returns Object

Smaller JSON
JSON.stringify({ id: 1, name: null }, U.json2replacer); // '{"id":1}'
property

U.queuecache

The state of the queues created by U.queue().

Returns Object

An object keyed by the queue name. Each item has limit, running and pending (the waiting callbacks). Read it for monitoring only.

Waiting items
var item = U.queuecache.import;
item && console.log(item.running, item.pending.length);
class

new U.EventEmitter2([obj])

A small event emitter.
ParameterTypeDescription
obj? Object An object to extend.

Returns EventEmitter2

new U.EventEmitter2() creates an emitter. U.EventEmitter2(obj) (without new) adds emit(), on(), once(), off(), removeListener() and removeAllListeners() to an existing object and returns it; U.EventEmitter2.extend(obj) does the same. Listeners are kept in $events. emit() passes up to 7 arguments and this is the emitter.

Extend an object
var service = {};
U.EventEmitter2(service);
service.on('ready', function(value) {
	console.log('ready', value);
});
service.emit('ready', 1);
method

emitter.off(name, [fn])

since 0.0.90 Removes a listener or all listeners of an event.
ParameterTypeDescription
name String The event name.
fn? Function The listener.

Returns EventEmitter2 The emitter.

Without fn all listeners of name are removed. removeListener() is an alias. removeAllListeners([name]) removes the listeners of one event or of all events.

Remove a listener
var fn = function() {};
emitter.on('change', fn);
emitter.off('change', fn);
method

U.Callback(count, [callback])

Calls a callback after next() was called count times.
ParameterTypeDescription
count Number How many next() calls to wait for.
callback? Function The function to call.

Returns Callback An instance with next() and done(fn).

Returns an instance with next() and done(callback). The callback runs once, when the pending count reaches zero. The class is also available as the global Callback.

Wait for 3 tasks
var cb = U.Callback(3, function() {
	console.log('all done');
});

for (var i = 0; i < 3; i++)
	setTimeout(() => cb.next(), 100 * i);
method

U.chunker(name, [max])

Stores many items in temporary files, page by page.
ParameterTypeDescription
name String A unique name, used in the file names.
max? Number The number of items per file. Default: 50

Returns Chunker

Every max items written with write() go to one file {name}-{index}.chunker in the temp directory, compressed with deflate. Read them back page by page with each() or read(). Properties: compress (default true), autoremove (default true, removes each file after it is read), count, pages and percentage (progress of each()). The class is available as U.Chunker.

Export in pages
var chunker = U.chunker('export', 100);

for (var item of items)
	chunker.write(item);

chunker.end();

chunker.each(function(items, next, index) {
	console.log('page', index, items.length);
	next();
}, function() {
	console.log('done');
});
method

chunker.write(item)

Adds an item.
ParameterTypeDescription
item Object An item that can be serialized to JSON.

Returns Chunker

When max items are waiting, they are written to a new file. append() is an alias. Call end() after the last item.

Write
chunker.write({ id: 1, name: 'Peter' });
method

chunker.end()

Writes the remaining items to the last file.

Returns Chunker

Finish writing
chunker.end();
method

chunker.each(onItem, [onEnd])

Reads all pages one by one.
ParameterTypeDescription
onItem Function function(items, next, index).
onEnd? Function Runs after the last page.

Returns Chunker

onItem(items, next, index) gets the items of one page; call next() to read the next page. onEnd() runs after the last page. percentage shows the progress.

Process pages
chunker.each(function(items, next) {
	items.wait(save, next);
}, () => console.log('done'));
method

chunker.read(index, callback)

Reads one page.
ParameterTypeDescription
index Number The page index from 0.
callback Function function(err, items).

Returns Chunker

callback(err, items) gets the items of the page, or an empty array when the file does not exist. It waits while files are still being written.

First page
chunker.read(0, function(err, items) {
	console.log(items);
});
method

chunker.clear()

Removes all files of the chunker.

Returns Chunker

destroy() also removes the files and releases the instance.

Clean up
chunker.clear();
method

U.reader([items])

Queries an array of objects with the NoSQL query builder.
ParameterTypeDescription
items? Array|Object|String The items or a URL.

Returns Reader

items is an array (or one object), or a URL of TextDB content that is downloaded and streamed. Without items, add data with reader.push(items) and finish with reader.push(null), or use reader.stream(stream). find(), list(), read(), count(), scalar(type, key, [key2]) and stats(groupfield, datefield, key, [type]) return a NoSQL query builder (where(), sort(), take(), callback()...). list() returns { page, pages, limit, count, items }. assign(data) creates a query from a serialized query object.

Filter an array
var reader = U.reader(users);

reader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {
	console.log(response);
});

reader.count().callback(function(err, response) {
	console.log(response);
});
method

reader.push(items)

Adds items to the reader.
ParameterTypeDescription
items Array|Object|null The data, or null at the end.

Returns undefined

Pass an array or one object for each chunk of data, then null to finish and get the results.

Push data
var reader = U.reader();
reader.find().where('active', true).callback(console.log);
reader.push(page1);
reader.push(page2);
reader.push(null);
method

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

Splits a stream of chunks into parts by delimiters.
ParameterTypeDescription
beg String|Buffer The delimiter or the start of a part.
end? String|Buffer The end of a part.
callback Function function(value, index).
skip? Number The number of parts to skip. Default: 0
stream? Stream A stream for the end event.

Returns Function function(chunk).

Returns function(chunk) that you pass every chunk to. Without end, every part ends with beg (and includes it), for example a line ending with \n. With end, every part starts with beg and ends with end. callback(value, index) gets each part as a string; return false to stop. skip skips the first parts. With stream, the remaining data is processed on the stream end event. U.streamer2() is the same but gives Buffers.

Read lines
var stream = F.Fs.createReadStream(PATH.databases('log.txt'));
stream.on('data', U.streamer('\n', function(line, index) {
	console.log(index, line.trim());
}, stream));
method

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

Same as U.streamer(), but the parts are Buffers.
ParameterTypeDescription
beg String|Buffer The delimiter or the start of a part.
end? String|Buffer The end of a part.
callback Function function(buffer, index).
skip? Number The number of parts to skip. Default: 0
stream? Stream A stream for the end event.

Returns Function function(chunk).

Binary parts
stream.on('data', U.streamer2('<item>', '</item>', function(buffer) {
	console.log(buffer.length);
}));
method

U.filestreamer(filename)

since 0.0.59 Reads a text file line by line in batches.
ParameterTypeDescription
filename String The file.

Returns Object A stream reader.

Returns a TextDB stream reader. Set ondocuments (called with this.docs, the lines of one batch joined by ,; return false to stop) and $callback (called at the end), then call openread(). Set array = true to get docs as an array of lines. Lines that start with - are skipped.

Read a JSON-lines file
var reader = U.filestreamer(PATH.databases('items.nosql'));
reader.ondocuments = function() {
	var items = JSON.parse('[' + reader.docs + ']');
	console.log(items.length);
};
reader.$callback = () => console.log('done');
reader.openread();
method

PATH.join(path1, [path2], [...])

since 0.0.39 Alias for Node.js path.join().
ParameterTypeDescription
path String One or more parts of the path.

Returns String

Join
var filename = PATH.join(PATH.root(), 'data', 'file.json');
method

PATH.exists(path, callback)

Checks that a file or directory exists.
ParameterTypeDescription
path String A path.
callback Function function(exists, size, isFile).

Returns undefined

callback(exists, size, isFile).

Check a file
PATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {
	console.log(exists, size, isFile);
});
method

PATH.verify(name)

Creates an app directory if it does not exist.
ParameterTypeDescription
name String The directory name.

Returns undefined

name is the name of a CONF.directory_{name} setting, for example databases. The check runs once per name.

Make sure the directory exists
PATH.verify('private');
method

PATH.ls(path, [callback], [filter], [unified])

Alias for U.ls().
ParameterTypeDescription
path String The directory.
callback? Function function(files, directories).

Returns Promise|undefined

PATH.ls2() is an alias for U.ls2().

List files
PATH.ls(PATH.private(), function(files) {
	console.log(files);
});
method

PATH.unlink(files, [callback])

Removes files one by one.
ParameterTypeDescription
files String|String Array The files.
callback? Function Runs at the end.

Returns undefined

Errors are ignored.

Remove files
PATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));
method

PATH.rmdir(directories, [callback])

Removes directories with all their content.
ParameterTypeDescription
directories String|String Array The directories.
callback? Function Runs at the end.

Returns undefined

Errors are ignored.

Remove a directory
PATH.rmdir(PATH.temp('import'), () => console.log('removed'));
method

PATH.private([filename])

Returns a path in the private directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_private (default /private/).

Path
var filename = PATH.private('data.json');
method

PATH.models([filename])

Returns a path in the models directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_models (default /models/).

Path
var filename = PATH.models('file.js');
method

PATH.builds([filename])

Returns a path in the builds directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_builds (default /builds/).

Path
var filename = PATH.builds('file.js');
method

PATH.views([filename])

Returns a path in the views directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_views (default /views/).

Path
var filename = PATH.views('index.html');
method

PATH.updates([filename])

Returns a path in the updates directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_updates (default /updates/).

Path
var filename = PATH.updates('file.js');
method

PATH.modules([filename])

Returns a path in the modules directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_modules (default /modules/).

Path
var filename = PATH.modules('file.js');
method

PATH.schemas([filename])

Returns a path in the schemas directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_schemas (default /schemas/).

Path
var filename = PATH.schemas('file.js');
method

PATH.extensions([filename])

Returns a path in the extensions directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_extensions (default /extensions/).

Path
var filename = PATH.extensions('file.js');
method

PATH.operations([filename])

Returns a path in the operations directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_operations (default /operations/).

Path
var filename = PATH.operations('file.js');
method

PATH.tasks([filename])

Returns a path in the tasks directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_tasks (default /tasks/).

Path
var filename = PATH.tasks('file.js');
method

PATH.controllers([filename])

Returns a path in the controllers directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_controllers (default /controllers/).

Path
var filename = PATH.controllers('file.js');
method

PATH.definitions([filename])

Returns a path in the definitions directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_definitions (default /definitions/).

Path
var filename = PATH.definitions('file.js');
method

PATH.tests([filename])

Returns a path in the tests directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_tests (default /tests/).

Path
var filename = PATH.tests('file.js');
method

PATH.services([filename])

Returns a path in the services directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_services (default /services/).

Path
var filename = PATH.services('file.js');
method

PATH.packages([filename])

Returns a path in the packages directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_packages (default /packages/).

Path
var filename = PATH.packages('file.js');
method

PATH.themes([filename])

Returns a path in the themes directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_themes (default /themes/).

Path
var filename = PATH.themes('default/index.html');
method

PATH.components([filename])

Returns a path in the components directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_components (default /components/).

Path
var filename = PATH.components('file.js');
method

PATH.templates([filename])

Returns a path in the templates directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_templates (default /templates/).

Path
var filename = PATH.templates('email.html');
method

PATH.plugins([filename])

since 0.0.88 Returns a path in the plugins directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_plugins (default /plugins/).

Path
var filename = PATH.plugins('file.js');
method

PATH.flowstreams([filename])

Returns a path in the flowstreams directory.
ParameterTypeDescription
filename? String A file name.

Returns String An absolute path.

The directory is CONF.directory_flowstreams (default /flowstreams/).

Path
var filename = PATH.flowstreams('file.js');
method

OBSOLETE(name, message)

Prints a warning about obsolete code.
ParameterTypeDescription
name String What is obsolete.
message String What to use instead.

It writes the date, the name and the message to the console and increases F.stats.other.obsolete. Nothing is printed when CONF.nowarnings is true (the framework sets it when the watcher restarts the application with --restart).

Warn
function oldsave(model) {
	OBSOLETE('oldsave()', 'Use save() instead.');
	return save(model);
}
method

UID1([type], [date])

Generates a unique identifier with a decimal time part.
ParameterTypeDescription
type? String A name of a separate counter.
date? Date The time of the identifier. Default: NOW

Returns String The identifier.

Like UID(), but the time part is the number of minutes since 2020-01-31 23:00 UTC written in decimal digits. Identifiers end with the version letter b. With type, every type has its own counter. date builds the identifier for another time.

Identifier
var id = UID1();
var orderid = UID1('orders');
Made in Europe