---
title: Utilities
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/utilities/
updated: 2026-11-18T16:57:29.576Z
---

# Utilities

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

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

## API

### U

Type: `property`

The Utils module as a global object.

Returns: `Object` The Utils module.

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

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

### UID()

Type: `method`

Returns a new unique identifier.

Returns: `String` For example `JacVuE1cn61f`.

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

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

### GUID([length])

Type: `method`

Returns a UUID-like string, or a random string of a given length.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | no |  | The number of characters. Omit it for the UUID-like format. |

Returns: `String`

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

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

### HASH(value, [type])

Type: `method`

Hashes a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The text to hash. |
| `type` | `String` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32` or `crc32unsigned`. |

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

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

Example: Hashes
```js
HASH('abc');            // 96354
HASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'
HASH(email, 'sha256');
```

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

Type: `method`

Makes a deep copy of an object or an array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object|Array` | yes |  | The value to copy. Other values are returned unchanged. |
| `skip` | `Object` | no |  | Keys to leave out, e.g. `{ password: 1 }`. |
| `nofunctions` | `Boolean` | no | `false` | `true` leaves out functions. |

Returns: `Object|Array` The copy.

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

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

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

Type: `method`

Copies the keys of one object into another.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object` | yes |  | The object to read. |
| `target` | `Object` | no |  | The object to write into. |
| `all` | `Boolean` | no | `true` | `false` writes only the keys that `target` already has. |

Returns: `Object` The target (or the new copy).

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

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

### DIFFARR(prop, db, form)

Type: `method`

Compares two arrays of objects by one property.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `prop` | `String` | yes |  | The key that identifies an item, e.g. `id`. |
| `db` | `Array` | yes |  | The current items (for example from the database). |
| `form` | `Array` | yes |  | The new items (for example from a form). |

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

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

Example: Synchronize items
```js
var diff = DIFFARR('id', current, model.items);

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

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

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

### QUERIFY([url], obj)

Type: `method`

Builds a query string from an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | A URL, optionally with a method in front. |
| `obj` | `Object` | yes |  | The values. |

Returns: `String`

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

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

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

Type: `method`

Calls a callback-style function and returns a promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | A function whose last argument is a callback. |
| `a` | `Object` | no |  | The first argument. |
| `b` | `Object` | no |  | The second argument. |
| `c` | `Object` | no |  | The third argument. |

Returns: `Promise`

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

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

### ERROR([name])

Type: `method`

Returns a callback that logs errors.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The name shown with the error, e.g. the function that failed. |

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

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

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

### print(...values)

Type: `method`

Writes values to the console.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `values` | `Object` | yes |  | The values to print. |

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

Example: Print
```js
print('Imported', count, 'products');
```

### NOW

Type: `property`

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

Returns: `Date`

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

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

### NOOP

Type: `property`

An empty function.

Returns: `Function`

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

Example: Ignore the result
```js
Fs.unlink(filename, NOOP);
```

### EMPTYOBJECT

Type: `property`

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

Returns: `Object`

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

Example: Defaults
```js
function find(filter) {
	var opt = filter || EMPTYOBJECT;
	var tags = opt.tags || EMPTYARRAY;
	return tags.length;
}
```

### MAIN

Type: `property`

A global object for the shared state of the application.

Returns: `Object`

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

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

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

### REPO

Type: `property`

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

Returns: `Object`

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

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

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

### FUNC

Type: `property`

A global object for your shared functions.

Returns: `Object`

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

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

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

### TEMP

Type: `property`

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

Returns: `Object`

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

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

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

### MODS

Type: `property`

The loaded modules by their id.

Returns: `Object`

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

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

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

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

Type: `method`

Stores a value in the in-memory cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key. |
| `value` | `Object` | yes |  | Any value. |
| `expire` | `String` | no | `'5 minutes'` | How long the value is valid. |

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

Example: Cache a result
```js
CACHE.set('products', items, '2 minutes');
```

### CACHE.get(key, [def])

Type: `method`

Reads a value from the in-memory cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key. |
| `def` | `Object` | no |  | The value returned when the key is missing or expired. |

Returns: `Object`

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

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

### CACHE.remove(key)

Type: `method`

Removes one value from the in-memory cache.

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

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

Example: Invalidate
```js
NOSQL('products').insert(model).callback(function() {
	CACHE.remove('products');
});
```

### CACHE.reset([search])

Type: `method`

Removes many values, or all of them.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `search` | `String|RegExp` | no |  | A part of the keys, or a pattern. |

Returns: `Number` The number of removed keys.

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

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

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

Type: `method`

Returns an object that is saved to a JSON file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The name of the file. |
| `delay` | `Number` | no | `10000` | Milliseconds between the last change and the write. |
| `skip` | `String|Array` | no |  | Keys not written to the file, as an array or a comma-separated string. |

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

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

Example: Settings that survive restarts
```js
var settings = MEMORIZE('settings', 'cache');

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

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

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

Type: `method`

Packs files and directories into one archive file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | The archive file to create (an existing file is replaced). |
| `files` | `String|Array` | yes |  | A directory, or paths relative to the root. |
| `callback` | `Function` | no |  | `function(err, meta)`. |
| `filter` | `Function` | no |  | `function(path, isdirectory)`; return `true` to pack the path. |

Returns: `Promise` When `callback` is omitted.

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

Example: Back up the uploads
```js
var meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {
	return isdir || !path.endsWith('.tmp');
});
print(meta.files, 'files', meta.size, 'bytes');
```

Example: Selected paths
```js
await BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);
```

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

Type: `method`

Unpacks an archive made by BACKUP().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | The archive. |
| `target` | `String` | yes |  | The directory to unpack into. |
| `callback` | `Function` | no |  | `function(err, meta)`. |
| `filter` | `Function` | no |  | `function(path, isdirectory)`. |

Returns: `Promise` When `callback` is omitted.

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

Example: Restore
```js
var meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));
print('Restored', meta.files, 'files');
```

Example: Skip files on the way
```js
RESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {
	err && print(err);
}, function(path, isdir) {
	if (!isdir && path.startsWith('/config'))
		return false;
});
```

### PATH.root([path])

Type: `method`

Returns the root directory of the application, or a path inside it.

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

Returns: `String` An absolute path.

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

Example: Paths
```js
PATH.root();                 // '/www/app'
PATH.root('config');         // '/www/app/config'
PATH.private('report.pdf');  // '/www/app/private/report.pdf'
```

### PATH.databases([path])

Type: `method`

Returns the databases directory, or a path inside it.

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

Returns: `String` An absolute path.

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

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

### PATH.temp([path])

Type: `method`

Returns the temporary directory, or a path inside it.

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

Returns: `String` An absolute path.

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

Example: A temporary file
```js
var filename = PATH.temp(UID() + '.csv');
```

### PATH.exists(path, [callback])

Type: `method`

Checks whether a file or a directory exists.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | An absolute path. |
| `callback` | `Function` | no |  | `function(exists, size, isfile)`. |

Returns: `Promise<Boolean>` When `callback` is omitted.

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

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

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

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

Type: `method`

Deletes one or more files.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `files` | `String|Array` | yes |  | An absolute path, or an array of paths. |
| `callback` | `Function` | no |  | `function()`. |

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

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

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

Type: `method`

Deletes directories with everything in them.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `directories` | `String|Array` | yes |  | An absolute path, or an array of paths. |
| `callback` | `Function` | no |  | `function()`. |

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

Example: Delete a directory
```js
PATH.rmdir(PATH.temp('export'), function() {
	print('Directory removed');
});
```

### Total.FsPromises

Type: `property`

The Node.js module `node:fs/promises`.

Returns: `Object` The module `node:fs/promises`.

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

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

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

Type: `method`

Converts any value to a number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value to convert. |
| `def` | `Number` | no | `0` | The result for empty or invalid values. |

Returns: `Number`

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

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

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

Type: `method`

Converts any value to a boolean.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value to convert. |
| `def` | `Boolean` | no | `false` | The result for `null` or `undefined`. |

Returns: `Boolean`

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

Example: A checkbox
```js
var newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true
```

### U.get(obj, path)

Type: `method`

Reads a nested value by a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The object to read. |
| `path` | `String` | yes |  | The path. |

Returns: `Object` The value, or `undefined`.

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

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

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

Type: `method`

Writes a nested value by a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The object to write into. |
| `path` | `String` | yes |  | The path. |
| `value` | `Object` | yes |  | The value. |

Returns: `Object` The written value.

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

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

Example: Path with an index
```js
var model = {};
U.set(model, 'items[0].name', 'Pen');
// { items: [{ name: 'Pen' }] }
```

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

Type: `method`

Copies the keys of source into target.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `target` | `Object` | yes |  | The object to write into. |
| `source` | `Object` | yes |  | The object to read. |
| `rewrite` | `Boolean` | no | `true` | `false` keeps existing values. |

Returns: `Object` The target.

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

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

### U.sortcomparer(sort)

Type: `method`

Returns a compare function for Array.sort().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `String` | yes |  | For example `name` or `price_desc,name`. |

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

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

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

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

Type: `method`

Returns a random integer in a range.

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

Returns: `Number`

Returns an integer between `min` and `max`, both included.

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 |  | The number of characters. |

Returns: `String`

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

Example: Random strings
```js
U.random_text(8);    // 'yb7JVb2a'
U.random_string(6);  // 'HNXkTk'
U.random_number(6);  // '825174'
```

### U.convert62(number)

Type: `method`

Converts a number to a base-62 string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `number` | `Number` | yes |  | A non-negative number. |

Returns: `String`

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

Example: Short codes
```js
var code = U.convert62(123456);  // 'W7E'
var id = U.from62(code);         // 123456
```

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

Type: `method`

Returns the extension of a file name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | A file name, a path or a URL. |
| `raw` | `Boolean` | no | `false` | `true` keeps the original case. |

Returns: `String`

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

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

### U.getName(path)

Type: `method`

Returns the last part of a path.

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

Returns: `String`

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

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

### U.getContentType(ext)

Type: `method`

Returns the MIME type for an extension.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ext` | `String` | yes |  | An extension, e.g. `png` or `.png`. |

Returns: `String`

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

Example: Content types
```js
U.getContentType('png');                     // 'image/png'
U.getContentType('.json');                   // 'application/json'
U.getExtensionFromContentType('image/png');  // 'png'
```

### U.btoa(value)

Type: `method`

Encodes text or a buffer to base64.

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

Returns: `String`

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

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

### U.validhost(host)

Type: `method`

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

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `host` | `String` | yes |  | The host name or IP address. |

Returns: `Boolean` `true` for a valid host.

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

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

### U.tohost(host)

Type: `method`

Converts a host name to its canonical ASCII form.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `host` | `String` | yes |  | The host name or IP address. |

Returns: `String` The canonical host, or an empty string.

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

Example: Convert hosts
```js
U.tohost('münchen.de');      // 'xn--mnchen-3ya.de'
U.tohost('EXAMPLE.com');     // 'example.com'
U.tohost('127.1');           // '127.0.0.1'
U.tohost('0x7f.0.0.1');      // '127.0.0.1'
U.tohost('evil.example\0.trusted.example'); // ''
```

Example: Validate input
```js
function host(value) {
	var host = U.tohost(value);
	if (!host)
		throw new Error('Invalid hostname');
	return host;
}
```

### U.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` | no |  | `function(err, success)`. |
| `timeout` | `Number` | no | `5000` | Milliseconds before the wait fails. |
| `interval` | `Number` | no | `500` | Milliseconds between checks. |

Returns: `Promise` When `callback` is omitted.

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

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

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

Type: `method`

Resolves the host of a URL to IPv4 addresses, with a cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | An absolute URL. |
| `callback` | `Function` | yes |  | `function(err, uri, param, addresses)`. |
| `param` | `Any` | no |  | A value passed to the callback. |

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

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

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

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

Type: `method`

Splits a stream of data into parts by delimiters.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `beg` | `String|Buffer` | yes |  | The start of a part, or the separator. |
| `end` | `String|Buffer` | no |  | The end of a part. |
| `callback` | `Function` | yes |  | `function(value, index)`; return `false` to stop. |
| `skip` | `Number` | no | `0` | The number of first parts to ignore. |
| `stream` | `Stream` | no |  | A stream whose `end` event flushes the rest. |

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

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

Example: Read a large XML file
```js
var stream = Fs.createReadStream(PATH.databases('products.xml'));
stream.on('data', U.streamer('<product>', '</product>', function(value, index) {
	var product = value.parseXML();
	print(index, product);
}));
```

Example: Lines of a CSV file
```js
var stream = Fs.createReadStream(filename);
stream.on('data', U.streamer('\n', function(line, index) {
	var cols = line.trim().split(';');
}, 1, stream));  // skips the header line
```

### U.connect(options, [callback])

Type: `method`

Opens a TCP or TLS connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes |  | `{ host, port, secure, tls, timeout }` and, with `secure`, other options of `tls.connect()`. |
| `callback` | `Function` | no |  | `function(err, meta)`. |

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

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

Example: Read the greeting of a server
```js
U.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {
	if (err) {
		console.log(err.message);
		return;
	}
	meta.ondata(function(chunk) {
		console.log(chunk.toString());
		meta.close();
	});
});
```

Example: Upgrade to TLS
```js
U.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {
	if (!err)
		console.log(meta.socket.encrypted); // true
});
```

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

Type: `method`

Lists the files and directories of a directory recursively.

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

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

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

Example: Find JSON files
```js
U.ls(PATH.databases(), function(files, directories) {
	print(files);
}, /\.json$/);
```

Example: Sizes with ls2
```js
var result = await U.ls2(PATH.public('uploads'));
var size = 0;
for (var file of result.files)
	size += file.stats.size;
```

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

Type: `method`

Stores a large list in temporary files, in pages.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A unique name, used for the file names. |
| `max` | `Number` | no | `50` | Items per page. |

Returns: `Chunker`

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

Example: Process a large export
```js
var chunker = U.chunker('export', 100);

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

chunker.end();

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

### chunker.load([callback])

Type: `method` · Since: `0.0.16`

Finds the pages that an earlier chunker with the same name left on disk.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `function(err, count)`. |

Returns: `Promise` When `callback` is omitted.

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

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

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

Type: `class`

A small event emitter.

Returns: `EventEmitter2`

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

Example: Events on your object
```js
var Cart = {};
U.EventEmitter2(Cart);

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

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

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

Type: `method`

Obfuscates a string with a key.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The text. |
| `key` | `String` | yes |  | The key. |
| `encode` | `String` | no | `'base64'` | The output encoding, or `buffer`. |

Returns: `String|Buffer`

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

Example: Round trip
```js
var data = U.encrypt_data('hello', 'mykey');
var text = U.decrypt_data(data, 'mykey');  // 'hello'
```

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

Type: `method`

Signs an identifier so that it cannot be changed.

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

Returns: `String`

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

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

### U.minify_js(value)

Type: `method`

Minifies JavaScript; U.minify_css() and U.minify_html() do the same for CSS and HTML.

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

Returns: `String`

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

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

### U.aistreamer(online, [onmessage])

Type: `method` · Since: `0.0.16`

Parses a streamed response of an AI chat API into lines of text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `online` | `Function` | yes |  | `function(line)`, called for each complete line of text. |
| `onmessage` | `Function` | no |  | `function(message)`, called for each parsed JSON message. |

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

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

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

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

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

Type: `method`

Caches the result of a task in a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | Identifier of the cached item. |
| `expire` | `String` | yes |  | How long the file is valid, for example `'5 minutes'`. |
| `callback` | `Function` | yes |  | `function(err, response)`. |
| `maker` | `Function` | yes |  | `function(next, id)` that creates the value. |
| `encoding` | `String` | no | `json` | `json` or a file encoding such as `utf8`. |

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

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