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

# Utilità

> Le funzioni di U (utils.js) e le funzioni di supporto e gli oggetti globali del framework.

Total.js definisce funzioni di supporto nello scope globale e nell'oggetto `U` (`Utils`), così ogni file di un'app può usarle senza `require()`. La guida [Utilità](../../guides/utilities/) spiega come usarle con esempi; questa pagina è il riferimento esatto.

## API

### U

Type: `property`

La libreria di utilità del framework (`utils.js`).

Returns: `Object`

`U`, `Utils` e `utils` sono lo stesso oggetto. È globale, quindi lo usi in controller, schemi, moduli e plugin senza `require()`.

Example: Usare una funzione di supporto
```js
var ext = U.getExtension('photo.JPG'); // 'jpg'
```

### Total

Type: `property` · Since: `0.0.96`

Un alias globale dell'istanza del framework `F`.

Returns: `Framework`

`Total`, `F` e `framework` fanno riferimento allo stesso oggetto.

Example: Stesso oggetto
```js
console.log(Total === F); // true
```

### NOW

Type: `property`

Un `Date` che il framework aggiorna regolarmente.

Returns: `Date`

Leggere `NOW` costa meno di `new Date()`. Il framework lo reimposta nei suoi intervalli interni (circa ogni minuto) e in alcune chiamate, come `LOGGER()`. Usalo quando basta una precisione di un minuto; usa `new Date()` per un orario esatto. `F.datetime` legge e scrive lo stesso valore.

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

### EMPTYOBJECT

Type: `property`

Un oggetto vuoto congelato.

Returns: `Object`

Usalo come valore predefinito che non viene mai modificato. È congelato, quindi le assegnazioni non hanno effetto.

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

### EMPTYARRAY

Type: `property`

Un array vuoto congelato.

Returns: `Array`

Usalo come valore predefinito che non viene mai modificato. È congelato, quindi `push()` solleva un errore.

Example: Elenco predefinito
```js
var items = response.items || EMPTYARRAY;
```

### NOOP()

Type: `method`

Una funzione vuota.

Returns: `undefined`

Passala dove è richiesta una callback e non ti serve il risultato.

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

### MAIN

Type: `property`

Un oggetto globale vuoto per i tuoi dati condivisi.

Returns: `Object`

Il framework crea `MAIN = {}` e non lo usa. Salvaci i valori validi per tutta l'applicazione, per esempio i dati caricati all'avvio.

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

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

### REPO

Type: `property`

Un oggetto globale vuoto per il tuo repository di valori.

Returns: `Object`

Il framework crea `REPO = {}` e non lo usa. È un secondo namespace come `MAIN`.

Example: Mettere in cache un elenco
```js
REPO.countries = ['SK', 'CZ', 'AT'];
```

### FUNC

Type: `property`

Un oggetto globale vuoto per le tue funzioni condivise.

Returns: `Object`

Il framework crea `FUNC = {}`. Mettici le funzioni di supporto che più file dell'app chiamano.

Example: Funzione condivisa
```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`

Un oggetto globale per dati temporanei che il framework svuota.

Returns: `Object`

Il framework sostituisce `TEMP` con un nuovo oggetto vuoto durante la sua pulizia periodica (ogni `CONF.default_interval_clear_cache` minuti, 10 per impostazione predefinita). Non tenerci nulla che ti serva in seguito.

Example: Valore di breve durata
```js
if (!TEMP.stats)
	TEMP.stats = compute();
```

### MODS

Type: `property`

Tutti i moduli caricati, per nome.

Returns: `Object`

Lo stesso oggetto di `F.modules`. Una chiave è il nome del file in `/modules/` (o l'`id` esportato dal modulo).

Example: Elencare i moduli
```js
Object.keys(MODS).forEach(function(name) {
	console.log(name);
});
```

### MODULE(name)

Type: `method`

Restituisce un modulo caricato.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del modulo. |

Returns: `Object` Il modulo, oppure `null`.

Legge `F.modules[name]`. Il risultato è l'`exports` del file del modulo, oppure `null` quando non è caricato alcun modulo con quel nome.

Example: Chiamare un modulo
```js
// modules/mailer.js
exports.send = function(email) { /* ... */ };

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

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

Type: `method`

Aggiunge una riga a un file di log nella directory `/logs/`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del file di log senza `.log`. |
| `value` | `Object` | yes |  | Uno o più valori da scrivere. |

Returns: `undefined`

La riga è `yyyy-MM-dd HH:mm:ss | values` nel file `{name}.log`. I valori sono separati da uno spazio; gli oggetti vengono formattati con `util.inspect()`. La directory viene creata quando non esiste, e le scritture passano per `U.queue()` con al massimo 5 scritture contemporanee.

Example: Registrare un pagamento
```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`

Chiama una funzione in stile callback e restituisce una Promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | Una funzione che accetta una callback come ultimo argomento. |
| `a` | `Object` | no |  | Primo argomento. |
| `b` | `Object` | no |  | Secondo argomento. |
| `c` | `Object` | no |  | Terzo argomento. |

Returns: `Promise`

`fn` viene chiamata con gli argomenti dati e una callback `function(err, response)` come ultimo argomento. La Promise viene rifiutata con `err` o si risolve con `response`. Sono supportati fino a tre argomenti; gli argomenti `undefined` non vengono passati.

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

Example: Una tua funzione
```js
function load(id, callback) {
	callback(null, { id: id });
}

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

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

Type: `method`

Attende finché una condizione è vera.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `validator` | `Function` | yes |  | Restituisce `true` quando l'attesa è finita. |
| `callback` | `Function` | yes |  | `function(err, success)`. |
| `timeout` | `Number` | no | `5000` | Tempo massimo in ms. |
| `interval` | `Number` | no | `500` | Tempo tra un controllo e l'altro in ms. |

Returns: `undefined`

`validator()` viene verificata subito e poi ogni `interval` ms. Quando restituisce `true`, viene chiamata `callback(null, true)`. Se trascorrono prima `timeout` ms, viene chiamata `callback(Error('Timeout'), false)`.

Example: Attendere una connessione
```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`

Crea un identificatore univoco breve.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no |  | Il nome di un contatore indipendente. |
| `date` | `Date` | no | `NOW` | Il tempo codificato nell'ID. |

Returns: `String`

L'ID è una stringa basata sul tempo, per esempio `24j0y001xn51d`, che si ordina in base al momento della creazione. È univoco all'interno dell'istanza in esecuzione (il framework aggiunge una chiave casuale dell'istanza). `type` mantiene un contatore separato per ogni tipo, così gli ID di collezioni diverse non condividono una sequenza. `date` crea l'ID per un altro momento. `CONF.default_uid` sceglie la versione: `r` produce un ID casuale (`UIDR()`), `f` una variante in base 62; quella predefinita è la versione `d`.

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

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

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

Type: `method`

Crea un identificatore univoco con la parte temporale in base 16.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no |  | Il nome di un contatore indipendente. |
| `date` | `Date` | no | `NOW` | Il tempo codificato nell'ID. |

Returns: `String`

Funziona come `UID()` ma codifica il tempo in esadecimale, quindi l'ID è un po' più lungo (versione `c`). Ignora `CONF.default_uid`.

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

### GUID([length])

Type: `method`

Crea un GUID o una stringa casuale di una lunghezza data.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | no |  | Lunghezza di una stringa casuale. |

Returns: `String`

Senza `length` restituisce una stringa nella forma UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` costruita dall'ora corrente e da numeri casuali. Con `length` restituisce lettere minuscole e cifre casuali di quella lunghezza. Disponibile anche come `U.GUID()`.

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

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

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

Type: `method`

Crea una copia profonda di un oggetto o di un array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | L'oggetto o l'array da copiare. |
| `skip` | `Object` | no |  | Chiavi da escludere, come `{ key: true }`. |
| `skipFunctions` | `Boolean` | no | `false` | Esclude le funzioni. |

Returns: `Object` Un nuovo oggetto.

Gli oggetti e gli array annidati vengono copiati; i valori `Date` ed `Error` vengono mantenuti per riferimento, e i Buffer vengono copiati. `skip` è un oggetto con le chiavi da escludere (`{ password: 1 }`) al primo livello degli oggetti. Disponibile anche come `U.clone()`.

Example: Copiare senza una chiave
```js
var copy = CLONE(user, { password: 1 });
copy.name = 'Peter'; // user.name is unchanged
```

### COPY(source, [target])

Type: `method`

Copia tutte le proprietà di `source` in `target`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object` | yes |  | Oggetto da leggere. |
| `target` | `Object` | no |  | Oggetto da scrivere. |

Returns: `Object` L'oggetto di destinazione.

Ogni chiave di `source` viene clonata in `target`, anche le chiavi che `target` non ha. Senza `target` restituisce una nuova copia di `source`. Equivale a `U.copy(source, target, true)`.

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

### HASH(value, [type])

Type: `method`

Crea un hash di una stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Il testo. |
| `type` | `String` | no |  | Un algoritmo di hash. |

Returns: `Number|String`

Senza `type` restituisce un hash numerico veloce (a 32 bit senza segno). `type` può essere `md5`, `sha1`, `sha256`, `sha512`, `crc32` o `crc32unsigned`. Chiama `value.hash()`.

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

### QUERIFY([url], obj)

Type: `method`

Aggiunge un oggetto a un URL come query string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | L'URL. |
| `obj` | `Object` | yes |  | Valori della query string. |

Returns: `String`

I valori `null` o `undefined` vengono esclusi; le date diventano stringhe ISO e gli array vengono uniti con virgole. Chiavi e valori vengono codificati. L'URL può iniziare con un metodo (`GET /api/`); la query viene aggiunta al percorso. Senza URL restituisce solo `?key=value`.

Example: Costruire un 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`

Confronta due array di oggetti in base a una chiave.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `prop` | `String` | yes |  | Nome della chiave, per esempio `id`. |
| `db` | `Object[]` | yes |  | Gli elementi salvati. |
| `form` | `Object[]` | yes |  | I nuovi elementi. |

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

Restituisce `{ add, upd, rem }`: `add` contiene gli elementi di `form` che non sono in `db`, `upd` contiene le coppie `{ db, form }` presenti in entrambi, e `rem` contiene i valori della chiave degli elementi di `db` che mancano in `form`. Usalo per salvare un elenco modificato da un utente.

Example: Sincronizzare un elenco
```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`

Restituisce un percorso nella directory radice dell'app.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un percorso relativo. |

Returns: `String`

Il risultato usa sempre `/` come separatore.

Example: Un file nella radice
```js
var filename = PATH.root('data/countries.json');
```

### PATH.temp([filename])

Type: `method`

Restituisce un percorso nella directory temporanea e crea la directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String`

La directory è `CONF.directory_temp`. `PATH.tmp()` e `PATH.temporary()` sono alias.

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

### PATH.databases([filename])

Type: `method`

Restituisce un percorso nella directory dei database e crea la directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String`

La directory è `CONF.directory_databases`.

Example: Un file di dati
```js
var filename = PATH.databases('settings.json');
```

### PATH.logs([filename])

Type: `method`

Restituisce un percorso nella directory dei log e crea la directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String`

La directory è `CONF.directory_logs`. `LOGGER()` scrive lì.

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

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

Type: `method`

Crea una directory con tutte le directory padre mancanti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Un percorso assoluto. |
| `cache` | `Boolean` | no | `false` | Salta i percorsi creati in precedenza. |

Returns: `undefined`

Funziona in modo sincrono. Con `cache` impostato su `true`, un percorso già creato non viene verificato di nuovo finché il framework non svuota la sua cache.

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

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

Type: `method`

Restituisce un intero casuale tra `min` e `max`, entrambi inclusi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | no | `100000` | Il valore più alto. |
| `min` | `Number` | no | `0` | Il valore più basso. |

Returns: `Number`

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

### U.random_text(length)

Type: `method`

Restituisce una stringa casuale di lettere e cifre.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | Numero di caratteri. |

Returns: `String`

I caratteri sono `0-9`, `A-Z` e `a-z`.

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

### U.random_string(length)

Type: `method`

Restituisce una stringa casuale di lettere.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | Numero di caratteri. |

Returns: `String`

I caratteri sono `A-Z` e `a-z`, senza cifre.

Example: Solo lettere
```js
var name = U.random_string(6);
```

### U.random_number(length)

Type: `method`

Restituisce una stringa di cifre casuali.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | Numero di cifre. |

Returns: `String`

La prima cifra non è mai `0`, quindi `+value` ha lo stesso numero di cifre. Il risultato è una stringa.

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

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

Type: `method`

Firma un ID in modo che il client non possa modificarlo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Number` | yes |  | L'ID. |
| `key` | `String` | no | `CONF.secret` | Una chiave segreta. |

Returns: `String`

Il risultato contiene l'ID e un checksum dell'ID e della chiave, per esempio `n3ck9tg6x123`. Il valore non è nascosto; è protetto dalle modifiche. Usa `U.decrypt_uid()` per rileggerlo.

Example: Link con un ID firmato
```js
var link = '/download/' + U.encrypt_uid(file.id) + '/';
```

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

Type: `method`

Legge un ID firmato da `U.encrypt_uid()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | L'ID firmato. |
| `key` | `String` | no | `CONF.secret` | La chiave segreta usata per firmarlo. |

Returns: `String|Number` L'ID, oppure `null`.

Restituisce l'ID originale (un numero quando è stato firmato un numero), oppure `null` quando il checksum non corrisponde.

Example: Verificare un ID da un URL
```js
var id = U.decrypt_uid(this.params.id);
if (id == null) {
	this.throw404();
	return;
}
```

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

Type: `method`

Copia i valori di `source` nelle chiavi che `target` ha già.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object` | yes |  | Oggetto da leggere. |
| `target` | `Object` | no |  | Oggetto da scrivere. |

Returns: `Object` L'oggetto di destinazione.

Vengono scritte solo le chiavi che esistono in `target` (con un valore diverso da `undefined`); i valori vengono clonati. Senza `target` restituisce una nuova copia di `source`. Per copiare tutte le chiavi, usa `COPY()`.

Example: Aggiornare i campi noti
```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`

Aggiunge le proprietà di `source` a `target`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `target` | `Object` | yes |  | Oggetto da scrivere. |
| `source` | `Object` | yes |  | Oggetto da leggere. |
| `rewrite` | `Boolean` | no | `true` | Sovrascrive i valori esistenti. |

Returns: `Object` L'oggetto di destinazione.

I valori vengono clonati. Con `rewrite` impostato su `false`, le chiavi che hanno già un valore in `target` vengono mantenute, quindi `source` funziona come un insieme di valori predefiniti.

Example: Valori predefiniti
```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`

Mantiene solo alcune proprietà di un oggetto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object|Object[]` | yes |  | L'oggetto o l'array di oggetti. |
| `props` | `String[]|Object` | yes |  | Chiavi da mantenere. |
| `reverse` | `Boolean` | no | `false` | Rimuove invece le chiavi elencate. |

Returns: `Object|Object[]`

`props` è un array di chiavi o un oggetto di cui vengono usate le chiavi. Con `reverse` impostato su `true`, le chiavi elencate vengono invece rimosse. Un array come `source` riduce ogni elemento. Il risultato è un nuovo oggetto.

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

### U.get(obj, path)

Type: `method`

Legge un valore tramite un percorso come `address.city`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | L'oggetto. |
| `path` | `String` | yes |  | Il percorso con i punti. |

Returns: `Object` Il valore.

Restituisce `undefined` quando una parte del percorso non esiste. Gli indici si scrivono come `items[0].name`. I percorsi che contengono caratteri simili a codice (spazi, parentesi di chiamate, `__proto__` e simili) restituiscono `undefined`.

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

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

Type: `method`

Scrive un valore tramite un percorso come `address.city`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | L'oggetto. |
| `path` | `String` | yes |  | Il percorso con i punti. |
| `value` | `Object` | yes |  | Il valore. |

Returns: `Object` Il valore.

Gli oggetti mancanti lungo il percorso vengono creati. Un percorso che termina con `[]` aggiunge il valore a un array. I percorsi che contengono caratteri simili a codice vengono ignorati.

Example: Costruire un oggetto
```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`

Rimuove gli spazi esterni da tutti i valori stringa di un oggetto o di un array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object|Array|String` | yes |  | Il valore da elaborare. |
| `clean` | `Boolean` | no | `false` | Sostituisce le stringhe vuote con `undefined`. |

Returns: `Object` Lo stesso valore.

Vengono elaborati anche gli oggetti e gli array annidati; l'oggetto viene modificato sul posto. Con `clean` impostato su `true`, le stringhe vuote diventano `undefined`.

Example: Pulire un 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`

Estrae le parole chiave da un testo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `content` | `String|String[]` | yes |  | Il testo. |
| `forSearch` | `Boolean` | no | `true` | Normalizza le parole per la ricerca. |
| `alternative` | `Boolean` | no | `false` | Accorcia le parole. |
| `max_count` | `Number` | no | `200` | Numero massimo di parole lette. |
| `max_length` | `Number` | no | `20` | Le parole più lunghe vengono saltate. |
| `min_length` | `Number` | no | `2` | Le parole più corte vengono saltate. |

Returns: `String[]`

Il testo viene convertito in minuscolo e diviso in parole; il risultato è un elenco di parole univoche, prima le più frequenti. Con `forSearch` (il valore predefinito), i segni diacritici vengono rimossi e `y` viene sostituito con `i`, così le stesse parole corrispondono in una ricerca. `alternative` accorcia ogni parola all'80 % della sua lunghezza per far corrispondere le forme delle parole. `content` può essere un array di testi.

Example: Indice di ricerca
```js
var keywords = U.keywords(product.name + ' ' + product.description).join(' ');
```

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

Type: `method`

Esegue funzioni con un limite al numero di esecuzioni contemporanee.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome della coda. |
| `max` | `Number` | yes |  | Numero massimo di funzioni in esecuzione. |
| `fn` | `Function` | yes |  | `function(next, param)`. |
| `param` | `Object` | no |  | Un valore passato a `fn`. |

Returns: `Boolean`

Ogni chiamata aggiunge `fn(next, param)` alla coda `name`. Al massimo `max` funzioni di quella coda vengono eseguite contemporaneamente; ognuna deve chiamare `next()` quando termina. Restituisce `true` quando `fn` parte subito, `false` quando resta in attesa.

Example: Tre download alla volta
```js
urls.forEach(function(url) {
	U.queue('downloads', 3, function(next, url) {
		download(url, next);
	}, url);
});
```

### U.sortcomparer(sort)

Type: `method`

Crea una funzione di confronto per `Array.sort()` a partire da un testo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `String` | yes |  | La definizione dell'ordinamento. |

Returns: `Function` `function(a, b)`

`sort` è un elenco di campi separati da virgole, ognuno con un suffisso facoltativo `_asc` o `_desc`, per esempio `price_desc,name`. Sono supportati campi annidati come `address.city`. Stringhe, numeri, booleani e date vengono confrontati in base al loro tipo.

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

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

Type: `method`

Unisce percorsi relativi alla directory radice dell'app.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Una o più parti del percorso. |

Returns: `String` Un percorso assoluto.

Una parte che inizia con `~` è un percorso assoluto e sostituisce ciò che la precede. Su Windows il risultato usa `/`.

Example: Percorsi nell'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`

Unisce parti di un percorso con `/`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Una o più parti. |

Returns: `String`

Gli slash all'inizio e alla fine di ogni parte vengono rimossi, e il risultato inizia con `/`. Le parti vuote vengono saltate.

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

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

Type: `method`

Restituisce l'estensione di un nome di file senza il punto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | Il nome del file o l'URL. |
| `raw` | `Boolean` | no | `false` | Mantiene maiuscole e minuscole originali. |

Returns: `String`

L'estensione viene convertita in minuscolo a meno che `raw` sia `true`. Una query string dopo `?` viene ignorata. Restituisce una stringa vuota quando non c'è estensione.

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

### U.getName(path)

Type: `method`

Restituisce l'ultima parte di un percorso.

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

Returns: `String`

Funziona con i separatori `/` e `\`; un separatore finale viene ignorato.

Example: Nome del file
```js
U.getName('/www/app/public/logo.png'); // 'logo.png'
```

### U.getContentType(ext)

Type: `method`

Restituisce il content type (tipo MIME) per un'estensione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ext` | `String` | yes |  | L'estensione. |

Returns: `String`

L'estensione può iniziare con un punto. Un'estensione sconosciuta restituisce `application/octet-stream`.

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

### U.setContentType(ext, type)

Type: `method`

Registra o modifica il content type di un'estensione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ext` | `String` | yes |  | L'estensione, con o senza punto. |
| `type` | `String` | yes |  | Il content type. |

Returns: `Boolean` `true`

Il framework usa la tabella per servire i file statici, quindi una nuova estensione diventa anche un file statico noto.

Example: Una nuova estensione
```js
// definitions/init.js
U.setContentType('gpx', 'application/gpx+xml');
```

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

Type: `method`

Elenca tutti i file e le directory in una directory e nelle sue sottodirectory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | La directory. |
| `callback` | `Function` | no |  | `function(files, directories)`. |
| `filter` | `String|RegExp|Function` | no |  | Un filtro. |
| `unified` | `Boolean` | no | `false` | Usa `/` su Windows. |

Returns: `Promise|undefined` Una Promise, senza callback.

`callback(files, directories)` riceve array di percorsi assoluti. Senza callback il metodo restituisce una Promise di `{ files, directories }`. `filter` è una stringa (parte del nome, senza distinzione tra maiuscole e minuscole), una RegExp, oppure `function(path, isDirectory)` che restituisce `true` per mantenere un elemento; i filtri stringa e RegExp si applicano solo ai file. Con `unified` impostato su `true`, i percorsi su Windows usano `/`.

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`

Elenca i file con le loro statistiche.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | La directory. |
| `callback` | `Function` | no |  | `function(files, directories)`. |
| `filter` | `String|RegExp|Function` | no |  | Un filtro. |
| `unified` | `Boolean` | no | `false` | Usa `/` su Windows. |

Returns: `Promise|undefined` Una Promise, senza callback.

Funziona come `U.ls()`, ma ogni file è `{ filename, stats }`, dove `stats` è l'oggetto `fs.Stats` (dimensione, date). Le directory restano percorsi.

Example: Dimensione totale
```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`

Codifica i caratteri speciali HTML.

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

Returns: `String`

`null` e `undefined` restituiscono una stringa vuota; gli altri valori vengono prima convertiti in stringa. Chiama `String.encode()`.

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

### U.decode(value)

Type: `method`

Decodifica le entità HTML riportandole a caratteri.

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

Returns: `String`

L'opposto di `U.encode()`. `null` e `undefined` restituiscono una stringa vuota.

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

### U.btoa(value)

Type: `method`

Codifica una stringa o un Buffer in Base64.

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

Returns: `String`

`U.atob(value)` decodifica il Base64 riportandolo a una stringa UTF-8.

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

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

Type: `method`

Analizza un XML e lo trasforma in un oggetto piatto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `xml` | `String` | yes |  | L'XML. |
| `replace` | `Boolean` | no | `false` | Sostituisce i caratteri speciali nelle chiavi. |

Returns: `Object`

Ogni chiave è il percorso di un elemento unito con punti, per esempio `root.item`; gli elementi ripetuti producono un array di valori. Gli attributi vengono salvati sotto la chiave con `[]`, per esempio `root.item[]`. Con `replace` impostato su `true`, i caratteri `[`, `]`, `:`, `.` e `_` nelle chiavi diventano `_`. Le sezioni CDATA vengono lette come testo.

Example: Leggere un 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`

Converte qualsiasi valore in un intero.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Il valore. |
| `def` | `Number` | no | `0` | Valore per un input vuoto o non valido. |

Returns: `Number`

`null`, `undefined` e una stringa vuota restituiscono `def`. Un numero viene restituito così com'è. `U.parseFloat(value, [def])` e `U.parseBoolean(value, [def])` funzionano allo stesso modo per decimali e booleani (`def` è `false` per i booleani; un numero è `true` quando è maggiore di 0).

Example: Valori della query
```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`

Restituisce la distanza tra due coordinate GPS in chilometri.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `lat1` | `Number` | yes |  | Latitudine del primo punto. |
| `lon1` | `Number` | yes |  | Longitudine del primo punto. |
| `lat2` | `Number` | yes |  | Latitudine del secondo punto. |
| `lon2` | `Number` | yes |  | Longitudine del secondo punto. |

Returns: `Number` Chilometri.

Usa la formula dell'emisenoverso (haversine) su una sfera con raggio di 6371 km; il risultato ha al massimo 3 cifre decimali.

Example: Da Bratislava a Praga
```js
U.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225
```

### U.minify_css(value)

Type: `method`

Minifica il CSS con il compilatore integrato.

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

Returns: `String`

Lo stesso compilatore che il framework usa per i file `.css` statici.

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

### U.minify_js(value)

Type: `method`

Minifica il JavaScript con il compilatore integrato.

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

Returns: `String`

Rimuove commenti e spazi bianchi. Lo stesso compilatore che il framework usa per i file `.js` statici.

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

### U.minify_html(value)

Type: `method`

Minifica l'HTML con il compilatore integrato.

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

Returns: `String`

Rimuove gli spazi bianchi tra i tag.

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

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

Type: `method` · Since: `0.0.63`

Salva uno stato con nome della tua app e lo passa a `DEF.onStatus(meta)`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String|Object` | yes |  | Il nome dello stato, oppure un oggetto `$`. |
| `data` | `Object` | yes |  | Qualsiasi valore. |
| `timeout` | `Number` | no |  | Ritarda l'aggiornamento e unisce le chiamate in questo intervallo, in millisecondi. |

Returns: `undefined` Niente.

Ogni `id` ha un oggetto di stato `{ id, data, date }`. `STATUS()` ne sostituisce `data`, imposta `date` e chiama `DEF.onStatus(meta)` quando lo definisci. Al posto di un `id` puoi passare un oggetto `$`; il suo `ID` (o `name`) è l'id.

Con `timeout` (in millisecondi), l'aggiornamento viene ritardato: la prima chiamata avvia il timer, le chiamate successive modificano solo `data`, e `DEF.onStatus()` viene eseguito una sola volta con gli ultimi dati quando il timer termina. Usalo per valori che cambiano spesso, come un avanzamento.

Con `CONF.allow_stats_status` (predefinito `true`), tutti gli stati vengono aggiunti come `status` allo snapshot delle statistiche che Total.js scrive in `<main script>.json` (`CONF.allow_stats_snapshot`).

Example: Avanzamento di un'importazione
```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`

Cifra una stringa con una chiave e una maschera casuale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Il testo da cifrare. |
| `key` | `String` | yes |  | La chiave. |
| `encode` | `String` | no | `base64` | Una codifica di Buffer oppure `buffer`. |

Returns: `String|Buffer` Il valore cifrato.

L'output cambia a ogni chiamata a causa di una maschera casuale di 4 byte. `encode` è una codifica di Buffer (predefinita `base64`); `buffer` restituisce il Buffer grezzo. Rileggilo con `U.decrypt_data()` e la stessa chiave. È un semplice offuscamento, non un sostituto di `U.encrypt_crypto()`.

Example: Cifrare una stringa JSON
```js
var token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);
```

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

Type: `method`

Decifra un valore creato da `U.encrypt_data()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Buffer` | yes |  | Il valore cifrato. |
| `key` | `String` | yes |  | La chiave usata per la cifratura. |
| `encode` | `String` | no | `base64` | La codifica di `value`. |

Returns: `String` Il testo decifrato oppure `null`.

`value` è una stringa nella codifica `encode` (predefinita `base64`) oppure un Buffer. Restituisce `null` quando il valore non può essere letto. Una chiave errata produce una stringa errata, non `null`, quindi verifica il risultato (per esempio con `parseJSON()`).

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

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

Type: `method`

Cifra i dati con un cifrario di Node.js.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | Il nome di un cifrario, per esempio `aes-256-cbc`. |
| `key` | `String` | yes |  | La chiave. |
| `value` | `String|Buffer` | yes |  | I dati. |

Returns: `Buffer` I dati cifrati.

Usa `Crypto.createCipheriv(type, key, CONF.default_crypto_iv)`. La lunghezza della chiave deve essere adatta al cifrario (32 caratteri per `aes-256-cbc`). `CONF.default_crypto_iv` viene creato dall'app per impostazione predefinita, quindi impostalo nella configurazione quando altre app devono decifrare i dati.

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`

Decifra i dati creati da `U.encrypt_crypto()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | Il nome del cifrario. |
| `key` | `String` | yes |  | La chiave. |
| `value` | `Buffer` | yes |  | I dati cifrati. |

Returns: `Buffer` I dati decifrati oppure `undefined`.

Usa `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Restituisce `undefined` quando i dati non possono essere decifrati.

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`

Converte un numero in una stringa in base 62.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `number` | `Number` | yes |  | Un numero positivo. |

Returns: `String`

L'alfabeto è composto da cifre, poi lettere maiuscole e minuscole. I decimali vengono arrotondati per difetto. Rileggilo con `U.from62()`.

Example: Codice breve
```js
U.convert62(123456789); // '8M0kX'
```

### U.from62(value)

Type: `method` · Since: `0.0.85`

Riconverte in numero una stringa in base 62 prodotta da `U.convert62()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Una stringa in base 62. |

Returns: `Number`

Example: Di nuovo in numero
```js
U.from62(U.convert62(1000)); // 1000
```

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

Type: `method` · Since: `0.0.88`

Restituisce un gruppo numerico di lunghezza fissa per un identificatore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | Un identificatore. |
| `count` | `Number` | no | `4` | Il numero di cifre. |

Returns: `String` Una stringa di cifre.

Il valore è `HASH(id, true)` modulo `10^count`, completato con zeri fino a `count` cifre. Lo stesso id produce sempre lo stesso gruppo, quindi è utile per distribuire i file in sottodirectory.

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

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

Type: `method`

Converte qualsiasi valore in un booleano.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Un valore. |
| `def` | `Boolean` | no | `false` | Il valore predefinito. |

Returns: `Boolean`

Un booleano viene restituito così com'è, un numero è `true` quando è maggiore di `0`, gli altri valori vengono convertiti in stringa e analizzati con `String.parseBoolean()`. `null` e `undefined` restituiscono `def`.

Example: Valore della query
```js
var active = U.parseBoolean($.query.active);
```

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

Type: `method`

Converte qualsiasi valore in un numero decimale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Un valore. |
| `def` | `Number` | no | `0` | Il valore predefinito. |

Returns: `Number`

Un numero viene restituito così com'è, gli altri valori vengono convertiti in stringa e analizzati con `String.parseFloat()`. `null`, `undefined` e una stringa vuota restituiscono `def`.

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

### U.isDate(value)

Type: `method`

Verifica che un valore sia un `Date` valido.

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

Returns: `Boolean`

Restituisce `false` per una data non valida come `new Date('abc')`.

Example: Validare una data
```js
U.isDate(new Date()); // true
U.isDate(new Date('abc')); // false
U.isDate('2024-01-01'); // false
```

### U.DAYS

Type: `property`

Nomi inglesi dei giorni della settimana.

Returns: `String Array`

L'array inizia con `Sunday`, quindi corrisponde a `Date.getDay()`.

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

### U.MONTHS

Type: `property`

Nomi inglesi dei mesi.

Returns: `String Array`

L'array inizia con `January`, quindi corrisponde a `Date.getMonth()`.

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

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

Type: `method`

Restituisce il testo di un codice di stato HTTP.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | yes |  | Un codice di stato HTTP. |
| `addCode` | `Boolean` | no | `true` | Aggiunge il codice al testo. |

Returns: `String`

Il testo proviene da `http.STATUS_CODES`. Con `addCode` (predefinito `true`) il codice viene aggiunto davanti.

Example: Testo dello stato
```js
U.httpstatus(404); // '404: Not Found'
U.httpstatus(404, false); // 'Not Found'
```

### U.toURLEncode(obj)

Type: `method`

Serializza un oggetto in una query string codificata per URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | Un oggetto. |

Returns: `String` Per esempio `q=total&page=2`.

Le stringhe vengono codificate con `encodeURIComponent()`, numeri e booleani vengono aggiunti così come sono, gli array vengono uniti con `,`. `null`, `undefined`, le stringhe vuote e gli altri oggetti (date incluse) vengono saltati. Restituisce una stringa vuota quando non viene aggiunto nulla.

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`

Decodifica una stringa base64 in una stringa UTF-8.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Una stringa base64. |

Returns: `String`

L'operazione inversa di `U.btoa()`.

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

### U.isrelative(url)

Type: `method`

Verifica che un URL sia relativo.

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

Returns: `Boolean`

Restituisce `false` quando l'URL inizia con `//` o contiene `http://` o `https://`.

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

### U.isStaticFile(url)

Type: `method`

Verifica che un URL sembri un file.

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

Returns: `Boolean`

Restituisce `true` quando gli ultimi 8 caratteri dell'URL contengono un punto, per esempio `/img/logo.png`.

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

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

Type: `method`

Risolve l'indirizzo IPv4 di un URL e lo mette in cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | Un URL. |
| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |
| `param` | `Object` | no |  | Un valore passato alla callback. |

Returns: `Array|undefined` Gli indirizzi in cache quando non viene fornita alcuna callback.

`callback(err, uri, param, addresses)` riceve l'URL analizzato con `uri.host` sostituito dal primo indirizzo. Gli indirizzi vengono messi in cache per host; senza callback il metodo restituisce gli indirizzi in cache (oppure `undefined`). Una risoluzione fallita viene ritentata una volta. Il comando `clear_dnscache` svuota la cache.

Example: Risoluzione DNS
```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`

Unisce parti di un URL con esattamente un `/` tra di esse.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Una o più parti dell'URL. |

Returns: `String`

A differenza di `U.join()`, non aggiunge un `/` iniziale e mantiene le parti così come sono.

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

### U.normalize(path)

Type: `method` · Since: `0.0.39`

Aggiunge `/` all'inizio e alla fine di un percorso quando manca.

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

Returns: `String`

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

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

Type: `method`

Aggiunge un delimitatore finale a un percorso quando manca.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Un percorso. |
| `delimiter` | `String` | no | `/` | Il delimitatore. |

Returns: `String`

Un percorso vuoto restituisce il delimitatore.

Example: Percorso di una directory
```js
U.path('/www/app'); // '/www/app/'
```

### U.getExtensionFromContentType(contentType)

Type: `method` · Since: `0.0.63`

Restituisce l'estensione di file di un content type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `contentType` | `String` | yes |  | Un content type. |

Returns: `String`

Cerca tra i content type noti a `U.getContentType()` (inclusi quelli aggiunti con `U.setContentType()`). Restituisce la prima corrispondenza senza punto, oppure `undefined`.

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

### U.ObjectToArray(obj)

Type: `method`

Converte un oggetto in un array di elementi `{ key, value }`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | Un oggetto. |

Returns: `Array`

`null` o `undefined` restituiscono `EMPTYARRAY`.

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

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

Type: `method`

Scorciatoia per `Buffer.from(value || '', encoding)`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array|Buffer` | no | `''` | I dati. |
| `encoding` | `String` | no | `utf8` | La codifica di una stringa. |

Returns: `Buffer`

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

### U.createBufferSize([size])

Type: `method`

Scorciatoia per `Buffer.alloc(size || 0)`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `size` | `Number` | no | `0` | La dimensione in byte. |

Returns: `Buffer` Un buffer riempito di zeri.

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

### U.json2replacer(key, value)

Type: `method`

Un replacer per `JSON.stringify()` che rimuove i valori `null` e `undefined`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | La chiave. |
| `value` | `Object` | yes |  | Il valore. |

Returns: `Object`

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

### U.queuecache

Type: `property`

Lo stato delle code create da `U.queue()`.

Returns: `Object`

Un oggetto con il nome della coda come chiave. Ogni elemento ha `limit`, `running` e `pending` (le callback in attesa). Leggilo solo a scopo di monitoraggio.

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

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

Type: `class`

Un piccolo emettitore di eventi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | no |  | Un oggetto da estendere. |

Returns: `EventEmitter2`

`new U.EventEmitter2()` crea un emettitore. `U.EventEmitter2(obj)` (senza `new`) aggiunge `emit()`, `on()`, `once()`, `off()`, `removeListener()` e `removeAllListeners()` a un oggetto esistente e lo restituisce; `U.EventEmitter2.extend(obj)` fa lo stesso. I listener vengono conservati in `$events`. `emit()` passa fino a 7 argomenti e `this` è l'emettitore.

Example: Estendere un oggetto
```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`

Rimuove un listener o tutti i listener di un evento.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'evento. |
| `fn` | `Function` | no |  | Il listener. |

Returns: `EventEmitter2` L'emettitore.

Senza `fn` vengono rimossi tutti i listener di `name`. `removeListener()` è un alias. `removeAllListeners([name])` rimuove i listener di un evento o di tutti gli eventi.

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

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

Type: `method`

Chiama una callback dopo che `next()` è stato chiamato `count` volte.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | Quante chiamate a `next()` attendere. |
| `callback` | `Function` | no |  | La funzione da chiamare. |

Returns: `Callback` Un'istanza con `next()` e `done(fn)`.

Restituisce un'istanza con `next()` e `done(callback)`. La callback viene eseguita una sola volta, quando il conteggio delle chiamate in sospeso arriva a zero. La classe è disponibile anche come `Callback` globale.

Example: Attendere 3 attività
```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`

Salva molti elementi in file temporanei, pagina per pagina.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Un nome univoco, usato nei nomi dei file. |
| `max` | `Number` | no | `50` | Il numero di elementi per file. |

Returns: `Chunker`

Ogni `max` elementi scritti con `write()` finiscono in un file `{name}-{index}.chunker` nella directory temporanea, compresso con deflate. Rileggili pagina per pagina con `each()` o `read()`. Proprietà: `compress` (predefinita `true`), `autoremove` (predefinita `true`, rimuove ogni file dopo averlo letto), `count`, `pages` e `percentage` (avanzamento di `each()`). La classe è disponibile come `U.Chunker`.

Example: Esportare a pagine
```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`

Aggiunge un elemento.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `item` | `Object` | yes |  | Un elemento che può essere serializzato in JSON. |

Returns: `Chunker`

Quando ci sono `max` elementi in attesa, vengono scritti in un nuovo file. `append()` è un alias. Chiama `end()` dopo l'ultimo elemento.

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

### chunker.end()

Type: `method`

Scrive gli elementi rimanenti nell'ultimo file.

Returns: `Chunker`

Example: Terminare la scrittura
```js
chunker.end();
```

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

Type: `method`

Legge tutte le pagine una alla volta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `onItem` | `Function` | yes |  | `function(items, next, index)`. |
| `onEnd` | `Function` | no |  | Eseguita dopo l'ultima pagina. |

Returns: `Chunker`

`onItem(items, next, index)` riceve gli elementi di una pagina; chiama `next()` per leggere la pagina successiva. `onEnd()` viene eseguita dopo l'ultima pagina. `percentage` mostra l'avanzamento.

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

### chunker.read(index, callback)

Type: `method`

Legge una pagina.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `index` | `Number` | yes |  | L'indice della pagina a partire da `0`. |
| `callback` | `Function` | yes |  | `function(err, items)`. |

Returns: `Chunker`

`callback(err, items)` riceve gli elementi della pagina, oppure un array vuoto quando il file non esiste. Attende finché i file sono ancora in scrittura.

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

### chunker.clear()

Type: `method`

Rimuove tutti i file del chunker.

Returns: `Chunker`

Anche `destroy()` rimuove i file e rilascia l'istanza.

Example: Pulizia
```js
chunker.clear();
```

### U.reader([items])

Type: `method`

Interroga un array di oggetti con il query builder NoSQL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `items` | `Array|Object|String` | no |  | Gli elementi o un URL. |

Returns: `Reader`

`items` è un array (o un singolo oggetto), oppure un URL di contenuto TextDB che viene scaricato e letto in streaming. Senza `items`, aggiungi i dati con `reader.push(items)` e termina con `reader.push(null)`, oppure usa `reader.stream(stream)`. `find()`, `list()`, `read()`, `count()`, `scalar(type, key, [key2])` e `stats(groupfield, datefield, key, [type])` restituiscono un query builder NoSQL (`where()`, `sort()`, `take()`, `callback()`...). `list()` restituisce `{ page, pages, limit, count, items }`. `assign(data)` crea una query da un oggetto query serializzato.

Example: Filtrare un 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`

Aggiunge elementi al reader.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `items` | `Array|Object|null` | yes |  | I dati, oppure `null` alla fine. |

Returns: `undefined`

Passa un array o un singolo oggetto per ogni blocco di dati, poi `null` per terminare e ottenere i risultati.

Example: Inserire dati
```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`

Divide uno stream di blocchi in parti tramite delimitatori.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `beg` | `String|Buffer` | yes |  | Il delimitatore o l'inizio di una parte. |
| `end` | `String|Buffer` | no |  | La fine di una parte. |
| `callback` | `Function` | yes |  | `function(value, index)`. |
| `skip` | `Number` | no | `0` | Il numero di parti da saltare. |
| `stream` | `Stream` | no |  | Uno stream per l'evento `end`. |

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

Restituisce `function(chunk)` a cui passi ogni blocco. Senza `end`, ogni parte termina con `beg` (e lo include), per esempio una riga che termina con `\n`. Con `end`, ogni parte inizia con `beg` e termina con `end`. `callback(value, index)` riceve ogni parte come stringa; restituisci `false` per fermarti. `skip` salta le prime parti. Con `stream`, i dati rimanenti vengono elaborati all'evento `end` dello stream. `U.streamer2()` è uguale ma fornisce dei Buffer.

Example: Leggere righe
```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`

Uguale a `U.streamer()`, ma le parti sono Buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `beg` | `String|Buffer` | yes |  | Il delimitatore o l'inizio di una parte. |
| `end` | `String|Buffer` | no |  | La fine di una parte. |
| `callback` | `Function` | yes |  | `function(buffer, index)`. |
| `skip` | `Number` | no | `0` | Il numero di parti da saltare. |
| `stream` | `Stream` | no |  | Uno stream per l'evento `end`. |

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

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

### U.filestreamer(filename)

Type: `method` · Since: `0.0.59`

Legge un file di testo riga per riga, a gruppi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | Il file. |

Returns: `Object` Uno stream reader.

Restituisce uno stream reader TextDB. Imposta `ondocuments` (chiamata con `this.docs`, le righe di un gruppo unite da `,`; restituisci `false` per fermarti) e `$callback` (chiamata alla fine), poi chiama `openread()`. Imposta `array = true` per ottenere `docs` come array di righe. Le righe che iniziano con `-` vengono saltate.

Example: Leggere un file JSON-lines
```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 di `path.join()` di Node.js.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Una o più parti del percorso. |

Returns: `String`

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

### PATH.exists(path, callback)

Type: `method`

Verifica che un file o una directory esista.

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

Returns: `undefined`

`callback(exists, size, isFile)`.

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

### PATH.verify(name)

Type: `method`

Crea una directory dell'app se non esiste.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome della directory. |

Returns: `undefined`

`name` è il nome di un'impostazione `CONF.directory_{name}`, per esempio `databases`. Il controllo viene eseguito una volta per nome.

Example: Assicurarsi che la directory esista
```js
PATH.verify('private');
```

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

Type: `method`

Alias di `U.ls()`.

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

Returns: `Promise|undefined`

`PATH.ls2()` è un alias di `U.ls2()`.

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

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

Type: `method`

Rimuove i file uno alla volta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `files` | `String|String Array` | yes |  | I file. |
| `callback` | `Function` | no |  | Eseguita alla fine. |

Returns: `undefined`

Gli errori vengono ignorati.

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

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

Type: `method`

Rimuove le directory con tutto il loro contenuto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `directories` | `String|String Array` | yes |  | Le directory. |
| `callback` | `Function` | no |  | Eseguita alla fine. |

Returns: `undefined`

Gli errori vengono ignorati.

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

### PATH.private([filename])

Type: `method`

Restituisce un percorso nella directory privata.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_private` (predefinita `/private/`).

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

### PATH.models([filename])

Type: `method`

Restituisce un percorso nella directory dei modelli.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_models` (predefinita `/models/`).

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

### PATH.builds([filename])

Type: `method`

Restituisce un percorso nella directory delle build.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_builds` (predefinita `/builds/`).

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

### PATH.views([filename])

Type: `method`

Restituisce un percorso nella directory delle viste.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_views` (predefinita `/views/`).

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

### PATH.updates([filename])

Type: `method`

Restituisce un percorso nella directory degli aggiornamenti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_updates` (predefinita `/updates/`).

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

### PATH.modules([filename])

Type: `method`

Restituisce un percorso nella directory dei moduli.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_modules` (predefinita `/modules/`).

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

### PATH.schemas([filename])

Type: `method`

Restituisce un percorso nella directory degli schemi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_schemas` (predefinita `/schemas/`).

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

### PATH.extensions([filename])

Type: `method`

Restituisce un percorso nella directory delle estensioni.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_extensions` (predefinita `/extensions/`).

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

### PATH.operations([filename])

Type: `method`

Restituisce un percorso nella directory delle operazioni.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_operations` (predefinita `/operations/`).

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

### PATH.tasks([filename])

Type: `method`

Restituisce un percorso nella directory delle attività.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_tasks` (predefinita `/tasks/`).

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

### PATH.controllers([filename])

Type: `method`

Restituisce un percorso nella directory dei controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_controllers` (predefinita `/controllers/`).

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

### PATH.definitions([filename])

Type: `method`

Restituisce un percorso nella directory delle definizioni.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_definitions` (predefinita `/definitions/`).

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

### PATH.tests([filename])

Type: `method`

Restituisce un percorso nella directory dei test.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_tests` (predefinita `/tests/`).

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

### PATH.services([filename])

Type: `method`

Restituisce un percorso nella directory dei servizi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_services` (predefinita `/services/`).

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

### PATH.packages([filename])

Type: `method`

Restituisce un percorso nella directory dei pacchetti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_packages` (predefinita `/packages/`).

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

### PATH.themes([filename])

Type: `method`

Restituisce un percorso nella directory dei temi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_themes` (predefinita `/themes/`).

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

### PATH.components([filename])

Type: `method`

Restituisce un percorso nella directory dei componenti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_components` (predefinita `/components/`).

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

### PATH.templates([filename])

Type: `method`

Restituisce un percorso nella directory dei template.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_templates` (predefinita `/templates/`).

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

### PATH.plugins([filename])

Type: `method` · Since: `0.0.88`

Restituisce un percorso nella directory dei plugin.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_plugins` (predefinita `/plugins/`).

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

### PATH.flowstreams([filename])

Type: `method`

Restituisce un percorso nella directory dei flowstream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | Un nome di file. |

Returns: `String` Un percorso assoluto.

La directory è `CONF.directory_flowstreams` (predefinita `/flowstreams/`).

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

### OBSOLETE(name, message)

Type: `method`

Stampa un avviso su codice obsoleto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Cosa è obsoleto. |
| `message` | `String` | yes |  | Cosa usare al suo posto. |

Scrive nella console la data, il nome e il messaggio e incrementa `F.stats.other.obsolete`. Non viene stampato nulla quando `CONF.nowarnings` è `true` (il framework lo imposta quando il watcher riavvia l'applicazione con `--restart`).

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

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

Type: `method`

Genera un identificatore univoco con una parte temporale decimale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no |  | Il nome di un contatore separato. |
| `date` | `Date` | no | `NOW` | Il momento dell'identificatore. |

Returns: `String` L'identificatore.

Come `UID()`, ma la parte temporale è il numero di minuti dal 2020-01-31 23:00 UTC scritto in cifre decimali. Gli identificatori terminano con la lettera di versione `b`. Con `type`, ogni tipo ha il proprio contatore. `date` costruisce l'identificatore per un altro momento.

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