---
title: Utilities
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/utilities/
updated: 2026-11-16T15:41:15.818Z
---

# Utilities

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

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](../../guides/utilities/) explains how to use them with examples; this page is the exact reference.

## API

### U

Type: `property`

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

Example: Use a helper
```js
var ext = U.getExtension('photo.JPG'); // 'jpg'
```

### Total

Type: `property` · Since: `0.0.96`

A global alias of the framework instance `F`.

Returns: `Framework`

`Total`, `F` and `framework` refer to the same object.

Example: Same object
```js
console.log(Total === F); // true
```

### NOW

Type: `property`

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.

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

### EMPTYOBJECT

Type: `property`

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.

Example: Default options
```js
function send(options) {
	options = options || EMPTYOBJECT;
	return options.timeout || 5000;
}
```

### EMPTYARRAY

Type: `property`

A frozen empty array.

Returns: `Array`

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

Example: Default list
```js
var items = response.items || EMPTYARRAY;
```

### NOOP()

Type: `method`

An empty function.

Returns: `undefined`

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

Example: Ignore a callback
```js
Fs.unlink(PATH.temp('export.csv'), NOOP);
```

### MAIN

Type: `property`

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.

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

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

### REPO

Type: `property`

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

Example: Cache a list
```js
REPO.countries = ['SK', 'CZ', 'AT'];
```

### FUNC

Type: `property`

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.

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

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

### TEMP

Type: `property`

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.

Example: Short-lived value
```js
if (!TEMP.stats)
	TEMP.stats = compute();
```

### MODS

Type: `property`

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

Example: List modules
```js
Object.keys(MODS).forEach(function(name) {
	console.log(name);
});
```

### MODULE(name)

Type: `method`

Returns a loaded module.

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

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

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

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

Type: `method`

Appends a line to a log file in the `/logs/` directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the log file without `.log`. |
| `value` | `Object` | yes |  | 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.

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

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

Type: `method` · Since: `0.0.97`

Calls a callback-style function and returns a Promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | A function that takes a callback as its last argument. |
| `a` | `Object` | no |  | First argument. |
| `b` | `Object` | no |  | Second argument. |
| `c` | `Object` | no |  | 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.

Example: Read a file
```js
var Fs = require('fs');
var content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');
```

Example: Your own function
```js
function load(id, callback) {
	callback(null, { id: id });
}

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

### WAIT(validator, callback, [timeout], [interval])

Type: `method`

Waits until a condition is true.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `validator` | `Function` | yes |  | Returns `true` when the wait is over. |
| `callback` | `Function` | yes |  | `function(err, success)`. |
| `timeout` | `Number` | no | `5000` | Maximum time in ms. |
| `interval` | `Number` | no | `500` | Time between checks in ms. |

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.

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

### UID([type], [date])

Type: `method`

Creates a short unique identifier.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no |  | A name of an independent counter. |
| `date` | `Date` | no | `NOW` | The time encoded in the ID. |

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.

Example: A new record
```js
var model = {};
model.id = UID();
model.dtcreated = NOW;
```

Example: Counter per type
```js
var orderid = UID('orders');
var invoiceid = UID('invoices');
```

### UID16([type], [date])

Type: `method`

Creates a unique identifier with the time part in base 16.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no |  | A name of an independent counter. |
| `date` | `Date` | no | `NOW` | The time encoded in the ID. |

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

Example: Hex-based ID
```js
var id = UID16(); // e.g. '367b52002xn60c'
```

### GUID([length])

Type: `method`

Creates a GUID or a random string of a given length.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | no |  | 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()`.

Example: UUID form
```js
var id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'
```

Example: Random token
```js
var token = GUID(30);
```

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

Type: `method`

Creates a deep copy of an object or an array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The object or array to copy. |
| `skip` | `Object` | no |  | Keys to leave out, as `{ key: true }`. |
| `skipFunctions` | `Boolean` | no | `false` | Leaves out functions. |

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

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

### COPY(source, [target])

Type: `method`

Copies all properties of `source` to `target`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object` | yes |  | Object to read. |
| `target` | `Object` | no |  | 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)`.

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

### HASH(value, [type])

Type: `method`

Creates a hash of a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The text. |
| `type` | `String` | no |  | 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()`.

Example: Numeric and MD5
```js
HASH('abc');        // 96354
HASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'
```

### QUERIFY([url], obj)

Type: `method`

Adds an object to a URL as a query string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | The URL. |
| `obj` | `Object` | yes |  | 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`.

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

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

### DIFFARR(prop, db, form)

Type: `method`

Compares two arrays of objects by a key.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `prop` | `String` | yes |  | Name of the key, for example `id`. |
| `db` | `Object[]` | yes |  | The stored items. |
| `form` | `Object[]` | yes |  | 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.

Example: Sync a list
```js
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]
```

### PATH.root([filename])

Type: `method`

Returns a path in the root directory of the app.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A relative path. |

Returns: `String`

The result always uses `/` as the separator.

Example: A file in the root
```js
var filename = PATH.root('data/countries.json');
```

### PATH.temp([filename])

Type: `method`

Returns a path in the temporary directory and creates the directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String`

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

Example: Temporary file
```js
var filename = PATH.temp('export-' + UID() + '.csv');
```

### PATH.databases([filename])

Type: `method`

Returns a path in the databases directory and creates the directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String`

The directory is `CONF.directory_databases`.

Example: A data file
```js
var filename = PATH.databases('settings.json');
```

### PATH.logs([filename])

Type: `method`

Returns a path in the logs directory and creates the directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String`

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

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

### PATH.mkdir(path, [cache])

Type: `method`

Creates a directory with all missing parent directories.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | An absolute path. |
| `cache` | `Boolean` | no | `false` | Skips paths created before. |

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.

Example: Directory for uploads
```js
var dir = PATH.databases('uploads/2021/');
PATH.mkdir(dir, true);
```

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

Type: `method`

Returns a random integer between `min` and `max`, both included.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | no | `100000` | The highest value. |
| `min` | `Number` | no | `0` | The lowest value. |

Returns: `Number`

Example: A dice
```js
var dice = U.random(6, 1);
```

### U.random_text(length)

Type: `method`

Returns a random string of letters and digits.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | Number of characters. |

Returns: `String`

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

Example: A code
```js
var code = U.random_text(8); // e.g. '1qrWGUa7'
```

### U.random_string(length)

Type: `method`

Returns a random string of letters.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | Number of characters. |

Returns: `String`

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

Example: Letters only
```js
var name = U.random_string(6);
```

### U.random_number(length)

Type: `method`

Returns a string of random digits.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | Number of digits. |

Returns: `String`

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

Example: A PIN
```js
var pin = U.random_number(6); // e.g. '986081'
```

### U.encrypt_uid(value, [key])

Type: `method`

Signs an ID so that it cannot be changed by the client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Number` | yes |  | The ID. |
| `key` | `String` | no | `CONF.secret` | A secret key. |

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.

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

### U.decrypt_uid(value, [key])

Type: `method`

Reads an ID signed by `U.encrypt_uid()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The signed ID. |
| `key` | `String` | no | `CONF.secret` | The secret key used to sign it. |

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.

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

### U.copy(source, [target])

Type: `method`

Copies the values of `source` to the keys that `target` already has.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object` | yes |  | Object to read. |
| `target` | `Object` | no |  | 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()`.

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

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

Type: `method`

Adds the properties of `source` to `target`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `target` | `Object` | yes |  | Object to write. |
| `source` | `Object` | yes |  | Object to read. |
| `rewrite` | `Boolean` | no | `true` | Overwrites existing values. |

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.

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

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

Type: `method`

Keeps only some properties of an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object|Object[]` | yes |  | The object or array of objects. |
| `props` | `String[]|Object` | yes |  | Keys to keep. |
| `reverse` | `Boolean` | no | `false` | Removes the listed keys instead. |

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.

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

### U.get(obj, path)

Type: `method`

Reads a value by a path such as `address.city`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The object. |
| `path` | `String` | yes |  | 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`.

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

### U.set(obj, path, value)

Type: `method`

Writes a value by a path such as `address.city`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The object. |
| `path` | `String` | yes |  | The path with dots. |
| `value` | `Object` | yes |  | 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.

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

### U.trim(obj, [clean])

Type: `method`

Trims all string values of an object or an array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object|Array|String` | yes |  | The value to trim. |
| `clean` | `Boolean` | no | `false` | Replaces empty strings with `undefined`. |

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

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

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

Type: `method`

Extracts keywords from a text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `content` | `String|String[]` | yes |  | The text. |
| `forSearch` | `Boolean` | no | `true` | Normalizes the words for search. |
| `alternative` | `Boolean` | no | `false` | Shortens the words. |
| `max_count` | `Number` | no | `200` | Maximum number of words read. |
| `max_length` | `Number` | no | `20` | Longer words are skipped. |
| `min_length` | `Number` | no | `2` | Shorter words are skipped. |

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.

Example: Search index
```js
var keywords = U.keywords(product.name + ' ' + product.description).join(' ');
```

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

Type: `method`

Runs functions with a limit of how many run at the same time.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the queue. |
| `max` | `Number` | yes |  | Maximum running functions. |
| `fn` | `Function` | yes |  | `function(next, param)`. |
| `param` | `Object` | no |  | 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.

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

### U.sortcomparer(sort)

Type: `method`

Creates a compare function for `Array.sort()` from a text.

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

Example: Sort products
```js
products.sort(U.sortcomparer('price_desc,name_asc'));
```

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

Type: `method`

Joins paths relative to the root directory of the app.

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

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

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

Type: `method`

Joins parts of a path with `/`.

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

Example: Join
```js
U.join('a', '/b/', 'c'); // '/a/b/c'
```

### U.getExtension(filename, [raw])

Type: `method`

Returns the extension of a file name without the dot.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | The file name or URL. |
| `raw` | `Boolean` | no | `false` | Keeps the original case. |

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.

Example: Extension
```js
U.getExtension('Photo.JPG?width=200'); // 'jpg'
```

### U.getName(path)

Type: `method`

Returns the last part of a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. |

Returns: `String`

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

Example: File name
```js
U.getName('/www/app/public/logo.png'); // 'logo.png'
```

### U.getContentType(ext)

Type: `method`

Returns the content type (MIME type) for an extension.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ext` | `String` | yes |  | The extension. |

Returns: `String`

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

Example: MIME type
```js
U.getContentType('json'); // 'application/json'
U.getContentType(U.getExtension(filename));
```

### U.setContentType(ext, type)

Type: `method`

Registers or changes the content type of an extension.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ext` | `String` | yes |  | The extension, with or without a dot. |
| `type` | `String` | yes |  | 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.

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

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

Type: `method`

Lists all files and directories in a directory and its subdirectories.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The directory. |
| `callback` | `Function` | no |  | `function(files, directories)`. |
| `filter` | `String|RegExp|Function` | no |  | A filter. |
| `unified` | `Boolean` | no | `false` | Uses `/` on Windows. |

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

Example: Callback
```js
U.ls(PATH.public(), function(files, directories) {
	console.log(files.length, directories.length);
}, /\.(jpg|png)$/);
```

Example: Promise
```js
var response = await U.ls(PATH.databases(), 'backup');
console.log(response.files);
```

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

Type: `method`

Lists files with their stats.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The directory. |
| `callback` | `Function` | no |  | `function(files, directories)`. |
| `filter` | `String|RegExp|Function` | no |  | A filter. |
| `unified` | `Boolean` | no | `false` | Uses `/` on Windows. |

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.

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

### U.encode(value)

Type: `method`

Encodes HTML special characters.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value. |

Returns: `String`

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

Example: Safe HTML
```js
U.encode('<b>'); // '&lt;b&gt;'
```

### U.decode(value)

Type: `method`

Decodes HTML entities back to characters.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value. |

Returns: `String`

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

Example: Plain text
```js
U.decode('&lt;b&gt;'); // '<b>'
```

### U.btoa(value)

Type: `method`

Encodes a string or a Buffer to Base64.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Buffer` | yes |  | The value. |

Returns: `String`

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

Example: Base64
```js
var encoded = U.btoa('hi'); // 'aGk='
var text = U.atob(encoded); // 'hi'
```

### U.parseXML(xml, [replace])

Type: `method`

Parses XML into a flat object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `xml` | `String` | yes |  | The XML. |
| `replace` | `Boolean` | no | `false` | Replaces special characters in keys. |

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.

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

### U.parseInt(value, [def])

Type: `method`

Converts any value to an integer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value. |
| `def` | `Number` | no | `0` | Value for empty or invalid input. |

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

Example: Query values
```js
var page = U.parseInt(this.query.page, 1);
var price = U.parseFloat(this.query.price);
var active = U.parseBoolean(this.query.active);
```

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

Type: `method`

Returns the distance between two GPS coordinates in kilometres.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `lat1` | `Number` | yes |  | Latitude of the first point. |
| `lon1` | `Number` | yes |  | Longitude of the first point. |
| `lat2` | `Number` | yes |  | Latitude of the second point. |
| `lon2` | `Number` | yes |  | 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.

Example: Bratislava to Prague
```js
U.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225
```

### U.minify_css(value)

Type: `method`

Minifies CSS with the built-in compiler.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | CSS code. |

Returns: `String`

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

Example: Minify
```js
U.minify_css('a { color: red; }'); // 'a{color:red}'
```

### U.minify_js(value)

Type: `method`

Minifies JavaScript with the built-in compiler.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | JavaScript code. |

Returns: `String`

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

Example: Minify
```js
U.minify_js('var a = 1;  // note');
```

### U.minify_html(value)

Type: `method`

Minifies HTML with the built-in compiler.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | HTML code. |

Returns: `String`

Removes white space between tags.

Example: Minify
```js
U.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'
```

### STATUS(id, data, [timeout])

Type: `method` · Since: `0.0.63`

Stores a named status of your app and passes it to `DEF.onStatus(meta)`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String|Object` | yes |  | The name of the status, or a `$` object. |
| `data` | `Object` | yes |  | Any value. |
| `timeout` | `Number` | no |  | 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`).

Example: Progress of an import
```js
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);
```

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

Type: `method`

Encrypts a string with a key and a random mask.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The text to encrypt. |
| `key` | `String` | yes |  | The key. |
| `encode` | `String` | no | `base64` | A Buffer encoding or `buffer`. |

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

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

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

Type: `method`

Decrypts a value made by `U.encrypt_data()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Buffer` | yes |  | The encrypted value. |
| `key` | `String` | yes |  | The key used for encryption. |
| `encode` | `String` | no | `base64` | The encoding of `value`. |

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

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

### U.encrypt_crypto(type, key, value)

Type: `method`

Encrypts data with a Node.js cipher.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | A cipher name, for example `aes-256-cbc`. |
| `key` | `String` | yes |  | The key. |
| `value` | `String|Buffer` | yes |  | 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.

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

### U.decrypt_crypto(type, key, value)

Type: `method`

Decrypts data made by `U.encrypt_crypto()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | The cipher name. |
| `key` | `String` | yes |  | The key. |
| `value` | `Buffer` | yes |  | 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.

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

### U.convert62(number)

Type: `method` · Since: `0.0.85`

Converts a number to a base-62 string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `number` | `Number` | yes |  | 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()`.

Example: Short code
```js
U.convert62(123456789); // '8M0kX'
```

### U.from62(value)

Type: `method` · Since: `0.0.85`

Converts a base-62 string from `U.convert62()` back to a number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | A base-62 string. |

Returns: `Number`

Example: Back to a number
```js
U.from62(U.convert62(1000)); // 1000
```

### U.groupify(id, [count])

Type: `method` · Since: `0.0.88`

Returns a fixed-length numeric group for an identifier.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | An identifier. |
| `count` | `Number` | no | `4` | The number of digits. |

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.

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

### U.parseBoolean(value, [def])

Type: `method`

Converts any value to a boolean.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | A value. |
| `def` | `Boolean` | no | `false` | The default value. |

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

Example: Query value
```js
var active = U.parseBoolean($.query.active);
```

### U.parseFloat(value, [def])

Type: `method`

Converts any value to a decimal number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | A value. |
| `def` | `Number` | no | `0` | The default value. |

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

Example: Price
```js
var price = U.parseFloat(model.price, 0);
```

### U.isDate(value)

Type: `method`

Checks that a value is a valid `Date`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | A value. |

Returns: `Boolean`

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

Example: Validate a date
```js
U.isDate(new Date()); // true
U.isDate(new Date('abc')); // false
U.isDate('2024-01-01'); // false
```

### U.DAYS

Type: `property`

English names of the days of the week.

Returns: `String Array`

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

Example: Day name
```js
var name = U.DAYS[new Date().getDay()];
```

### U.MONTHS

Type: `property`

English names of the months.

Returns: `String Array`

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

Example: Month name
```js
var name = U.MONTHS[new Date().getMonth()];
```

### U.httpstatus(code, [addCode])

Type: `method`

Returns the text of an HTTP status code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | yes |  | An HTTP status code. |
| `addCode` | `Boolean` | no | `true` | Adds the code to the text. |

Returns: `String`

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

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

### U.toURLEncode(obj)

Type: `method`

Serializes an object into a URL-encoded query string.

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

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

### U.atob(value)

Type: `method`

Decodes a base64 string to a UTF-8 string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | A base64 string. |

Returns: `String`

The reverse of `U.btoa()`.

Example: Decode
```js
U.atob(U.btoa('Hello')); // 'Hello'
```

### U.isrelative(url)

Type: `method`

Checks that a URL is relative.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | A URL. |

Returns: `Boolean`

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

Example: Safe redirect
```js
var url = $.query.redirect || '/';
if (!U.isrelative(url))
	url = '/';
$.redirect(url);
```

### U.isStaticFile(url)

Type: `method`

Checks that a URL looks like a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | A URL path. |

Returns: `Boolean`

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

Example: File or route
```js
U.isStaticFile('/img/logo.png'); // true
U.isStaticFile('/api/users/'); // false
```

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

Type: `method`

Resolves the IPv4 address of a URL and caches it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | A URL. |
| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |
| `param` | `Object` | no |  | 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.

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

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

Type: `method` · Since: `0.0.39`

Joins URL parts with exactly one `/` between them.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | One or more URL parts. |

Returns: `String`

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

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

### U.normalize(path)

Type: `method` · Since: `0.0.39`

Adds `/` to the start and the end of a path when it is missing.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | A path. |

Returns: `String`

Example: Normalize
```js
U.normalize('admin'); // '/admin/'
```

### U.path(path, [delimiter])

Type: `method`

Adds a trailing delimiter to a path when it is missing.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | A path. |
| `delimiter` | `String` | no | `/` | The delimiter. |

Returns: `String`

An empty path returns the delimiter.

Example: Directory path
```js
U.path('/www/app'); // '/www/app/'
```

### U.getExtensionFromContentType(contentType)

Type: `method` · Since: `0.0.63`

Returns the file extension of a content type.

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

Example: Extension
```js
U.getExtensionFromContentType('image/png'); // 'png'
```

### U.ObjectToArray(obj)

Type: `method`

Converts an object into an array of `{ key, value }` items.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | An object. |

Returns: `Array`

`null` or `undefined` returns `EMPTYARRAY`.

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

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

Type: `method`

Shortcut for `Buffer.from(value || '', encoding)`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array|Buffer` | no | `''` | The data. |
| `encoding` | `String` | no | `utf8` | The encoding of a string. |

Returns: `Buffer`

Example: From base64
```js
var buffer = U.createBuffer(body, 'base64');
```

### U.createBufferSize([size])

Type: `method`

Shortcut for `Buffer.alloc(size || 0)`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `size` | `Number` | no | `0` | The size in bytes. |

Returns: `Buffer` A buffer filled with zeros.

Example: Empty buffer
```js
var buffer = U.createBufferSize(4);
buffer.writeInt32BE(100);
```

### U.json2replacer(key, value)

Type: `method`

A `JSON.stringify()` replacer that removes `null` and `undefined` values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key. |
| `value` | `Object` | yes |  | The value. |

Returns: `Object`

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

### U.queuecache

Type: `property`

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.

Example: Waiting items
```js
var item = U.queuecache.import;
item && console.log(item.running, item.pending.length);
```

### new U.EventEmitter2([obj])

Type: `class`

A small event emitter.

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

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

### emitter.off(name, [fn])

Type: `method` · Since: `0.0.90`

Removes a listener or all listeners of an event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name. |
| `fn` | `Function` | no |  | 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.

Example: Remove a listener
```js
var fn = function() {};
emitter.on('change', fn);
emitter.off('change', fn);
```

### U.Callback(count, [callback])

Type: `method`

Calls a callback after `next()` was called `count` times.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | How many `next()` calls to wait for. |
| `callback` | `Function` | no |  | 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`.

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

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

### U.chunker(name, [max])

Type: `method`

Stores many items in temporary files, page by page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A unique name, used in the file names. |
| `max` | `Number` | no | `50` | The number of items per file. |

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

Example: Export in pages
```js
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');
});
```

### chunker.write(item)

Type: `method`

Adds an item.

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

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

### chunker.end()

Type: `method`

Writes the remaining items to the last file.

Returns: `Chunker`

Example: Finish writing
```js
chunker.end();
```

### chunker.each(onItem, [onEnd])

Type: `method`

Reads all pages one by one.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `onItem` | `Function` | yes |  | `function(items, next, index)`. |
| `onEnd` | `Function` | no |  | 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.

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

### chunker.read(index, callback)

Type: `method`

Reads one page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `index` | `Number` | yes |  | The page index from `0`. |
| `callback` | `Function` | yes |  | `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.

Example: First page
```js
chunker.read(0, function(err, items) {
	console.log(items);
});
```

### chunker.clear()

Type: `method`

Removes all files of the chunker.

Returns: `Chunker`

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

Example: Clean up
```js
chunker.clear();
```

### U.reader([items])

Type: `method`

Queries an array of objects with the NoSQL query builder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `items` | `Array|Object|String` | no |  | 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.

Example: Filter an array
```js
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);
});
```

### reader.push(items)

Type: `method`

Adds items to the reader.

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

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

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

Type: `method`

Splits a stream of chunks into parts by delimiters.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `beg` | `String|Buffer` | yes |  | The delimiter or the start of a part. |
| `end` | `String|Buffer` | no |  | The end of a part. |
| `callback` | `Function` | yes |  | `function(value, index)`. |
| `skip` | `Number` | no | `0` | The number of parts to skip. |
| `stream` | `Stream` | no |  | 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.

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

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

Type: `method`

Same as `U.streamer()`, but the parts are Buffers.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `beg` | `String|Buffer` | yes |  | The delimiter or the start of a part. |
| `end` | `String|Buffer` | no |  | The end of a part. |
| `callback` | `Function` | yes |  | `function(buffer, index)`. |
| `skip` | `Number` | no | `0` | The number of parts to skip. |
| `stream` | `Stream` | no |  | A stream for the `end` event. |

Returns: `Function` `function(chunk)`.

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

### U.filestreamer(filename)

Type: `method` · Since: `0.0.59`

Reads a text file line by line in batches.

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

Example: Read a JSON-lines file
```js
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();
```

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

Type: `method` · Since: `0.0.39`

Alias for Node.js `path.join()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | One or more parts of the path. |

Returns: `String`

Example: Join
```js
var filename = PATH.join(PATH.root(), 'data', 'file.json');
```

### PATH.exists(path, callback)

Type: `method`

Checks that a file or directory exists.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | A path. |
| `callback` | `Function` | yes |  | `function(exists, size, isFile)`. |

Returns: `undefined`

`callback(exists, size, isFile)`.

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

### PATH.verify(name)

Type: `method`

Creates an app directory if it does not exist.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The directory name. |

Returns: `undefined`

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

Example: Make sure the directory exists
```js
PATH.verify('private');
```

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

Type: `method`

Alias for `U.ls()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The directory. |
| `callback` | `Function` | no |  | `function(files, directories)`. |

Returns: `Promise|undefined`

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

Example: List files
```js
PATH.ls(PATH.private(), function(files) {
	console.log(files);
});
```

### PATH.unlink(files, [callback])

Type: `method`

Removes files one by one.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `files` | `String|String Array` | yes |  | The files. |
| `callback` | `Function` | no |  | Runs at the end. |

Returns: `undefined`

Errors are ignored.

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

### PATH.rmdir(directories, [callback])

Type: `method`

Removes directories with all their content.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `directories` | `String|String Array` | yes |  | The directories. |
| `callback` | `Function` | no |  | Runs at the end. |

Returns: `undefined`

Errors are ignored.

Example: Remove a directory
```js
PATH.rmdir(PATH.temp('import'), () => console.log('removed'));
```

### PATH.private([filename])

Type: `method`

Returns a path in the private directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.private('data.json');
```

### PATH.models([filename])

Type: `method`

Returns a path in the models directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.models('file.js');
```

### PATH.builds([filename])

Type: `method`

Returns a path in the builds directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.builds('file.js');
```

### PATH.views([filename])

Type: `method`

Returns a path in the views directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.views('index.html');
```

### PATH.updates([filename])

Type: `method`

Returns a path in the updates directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.updates('file.js');
```

### PATH.modules([filename])

Type: `method`

Returns a path in the modules directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.modules('file.js');
```

### PATH.schemas([filename])

Type: `method`

Returns a path in the schemas directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.schemas('file.js');
```

### PATH.extensions([filename])

Type: `method`

Returns a path in the extensions directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.extensions('file.js');
```

### PATH.operations([filename])

Type: `method`

Returns a path in the operations directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.operations('file.js');
```

### PATH.tasks([filename])

Type: `method`

Returns a path in the tasks directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.tasks('file.js');
```

### PATH.controllers([filename])

Type: `method`

Returns a path in the controllers directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.controllers('file.js');
```

### PATH.definitions([filename])

Type: `method`

Returns a path in the definitions directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.definitions('file.js');
```

### PATH.tests([filename])

Type: `method`

Returns a path in the tests directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.tests('file.js');
```

### PATH.services([filename])

Type: `method`

Returns a path in the services directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.services('file.js');
```

### PATH.packages([filename])

Type: `method`

Returns a path in the packages directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.packages('file.js');
```

### PATH.themes([filename])

Type: `method`

Returns a path in the themes directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.themes('default/index.html');
```

### PATH.components([filename])

Type: `method`

Returns a path in the components directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.components('file.js');
```

### PATH.templates([filename])

Type: `method`

Returns a path in the templates directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.templates('email.html');
```

### PATH.plugins([filename])

Type: `method` · Since: `0.0.88`

Returns a path in the plugins directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.plugins('file.js');
```

### PATH.flowstreams([filename])

Type: `method`

Returns a path in the flowstreams directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name. |

Returns: `String` An absolute path.

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

Example: Path
```js
var filename = PATH.flowstreams('file.js');
```

### OBSOLETE(name, message)

Type: `method`

Prints a warning about obsolete code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | What is obsolete. |
| `message` | `String` | yes |  | 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`).

Example: Warn
```js
function oldsave(model) {
	OBSOLETE('oldsave()', 'Use save() instead.');
	return save(model);
}
```

### UID1([type], [date])

Type: `method`

Generates a unique identifier with a decimal time part.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no |  | A name of a separate counter. |
| `date` | `Date` | no | `NOW` | The time of the identifier. |

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.

Example: Identifier
```js
var id = UID1();
var orderid = UID1('orders');
```
